Body-language reference

robot.body_language

Body Language Engine - high-level servo choreography.

The :class:BodyLanguageEngine consumes requests like :class:LookLeft, :class:HeadNod, :class:Wave, :class:Celebrate, :class:ArmsRelax and translates them into coordinated servo motions on the four-servo chassis. It is the only component that talks to the :class:ServoController for expressive motion.

The engine never knows about emotions directly. The EmotionEngine emits a :class:BodyLanguageHint (head-tilt + arm-pose) which the body-language engine interprets.

Requests

robot.body_language.requests

Body language request types.

A request is a high-level intent the body-language engine knows how to perform. Each request knows how to translate itself into a :class:ServoTimeline (a list of concurrent + sequential servo animations).

CENTER = 90.0 module-attribute

DEFAULT_CALIBRATION = {SERVO_HEAD_PAN: ServoCalibration(SERVO_HEAD_PAN, 30.0, 150.0, 90.0), SERVO_HEAD_TILT: ServoCalibration(SERVO_HEAD_TILT, 45.0, 135.0, 90.0), SERVO_LEFT_ARM: ServoCalibration(SERVO_LEFT_ARM, 20.0, 160.0, 90.0), SERVO_RIGHT_ARM: ServoCalibration(SERVO_RIGHT_ARM, 20.0, 160.0, 90.0)} module-attribute

MAX = 160.0 module-attribute

MIN = 20.0 module-attribute

SERVO_HEAD_PAN = 'pan' module-attribute

SERVO_HEAD_TILT = 'tilt' module-attribute

SERVO_LEFT_ARM = 'left_arm' module-attribute

SERVO_RIGHT_ARM = 'right_arm' module-attribute

__all__ = ['DEFAULT_CALIBRATION', 'SERVO_HEAD_PAN', 'SERVO_HEAD_TILT', 'SERVO_LEFT_ARM', 'SERVO_RIGHT_ARM', 'ArmsOpen', 'ArmsRelax', 'BodyRequest', 'Celebrate', 'Greet', 'HeadNod', 'HeadTiltRequest', 'LookLeft', 'LookRight', 'ServoCalibration', 'ServoFrame', 'Shrug', 'Wave'] module-attribute

ArmsOpen dataclass

Bases: _BaseRequest

Source code in src/robot/body_language/requests.py
@dataclass(slots=True, frozen=True)
class ArmsOpen(_BaseRequest):
    name: str = "arms_open"
    amount: float = 20.0
    duration_s: float = 0.5

    def frames(self) -> list[ServoFrame]:
        return [
            ServoFrame(
                targets={
                    SERVO_LEFT_ARM: max(MIN, min(MAX, CENTER - self.amount)),
                    SERVO_RIGHT_ARM: max(MIN, min(MAX, CENTER + self.amount)),
                },
                duration_s=self.duration_s,
            )
        ]

amount = 20.0 class-attribute instance-attribute

duration_s = 0.5 class-attribute instance-attribute

name = 'arms_open' class-attribute instance-attribute

__init__(name='arms_open', amount=20.0, duration_s=0.5)

frames()

Source code in src/robot/body_language/requests.py
def frames(self) -> list[ServoFrame]:
    return [
        ServoFrame(
            targets={
                SERVO_LEFT_ARM: max(MIN, min(MAX, CENTER - self.amount)),
                SERVO_RIGHT_ARM: max(MIN, min(MAX, CENTER + self.amount)),
            },
            duration_s=self.duration_s,
        )
    ]

ArmsRelax dataclass

Bases: _BaseRequest

Source code in src/robot/body_language/requests.py
@dataclass(slots=True, frozen=True)
class ArmsRelax(_BaseRequest):
    name: str = "arms_relax"
    duration_s: float = 0.5

    def frames(self) -> list[ServoFrame]:
        return [
            ServoFrame(
                targets={SERVO_LEFT_ARM: CENTER, SERVO_RIGHT_ARM: CENTER},
                duration_s=self.duration_s,
            )
        ]

duration_s = 0.5 class-attribute instance-attribute

name = 'arms_relax' class-attribute instance-attribute

__init__(name='arms_relax', duration_s=0.5)

frames()

Source code in src/robot/body_language/requests.py
def frames(self) -> list[ServoFrame]:
    return [
        ServoFrame(
            targets={SERVO_LEFT_ARM: CENTER, SERVO_RIGHT_ARM: CENTER},
            duration_s=self.duration_s,
        )
    ]

BodyRequest

Bases: Protocol

A high-level body-language request.

Source code in src/robot/body_language/requests.py
@runtime_checkable
class BodyRequest(Protocol):
    """A high-level body-language request."""

    @property
    def name(self) -> str: ...

    def frames(self) -> list[ServoFrame]: ...

name property

frames()

Source code in src/robot/body_language/requests.py
def frames(self) -> list[ServoFrame]: ...

Celebrate dataclass

Bases: _BaseRequest

Source code in src/robot/body_language/requests.py
@dataclass(slots=True, frozen=True)
class Celebrate(_BaseRequest):
    name: str = "celebrate"
    duration_s: float = 0.6

    def frames(self) -> list[ServoFrame]:
        up = max(MIN, min(MAX, CENTER - 40.0))
        return [
            ServoFrame(
                targets={
                    SERVO_LEFT_ARM: up,
                    SERVO_RIGHT_ARM: up,
                    SERVO_HEAD_TILT: max(MIN, min(MAX, CENTER - 20.0)),
                },
                duration_s=self.duration_s / 2,
            ),
            ServoFrame(
                targets={SERVO_LEFT_ARM: CENTER, SERVO_RIGHT_ARM: CENTER, SERVO_HEAD_TILT: CENTER},
                duration_s=self.duration_s / 2,
            ),
        ]

duration_s = 0.6 class-attribute instance-attribute

name = 'celebrate' class-attribute instance-attribute

__init__(name='celebrate', duration_s=0.6)

frames()

Source code in src/robot/body_language/requests.py
def frames(self) -> list[ServoFrame]:
    up = max(MIN, min(MAX, CENTER - 40.0))
    return [
        ServoFrame(
            targets={
                SERVO_LEFT_ARM: up,
                SERVO_RIGHT_ARM: up,
                SERVO_HEAD_TILT: max(MIN, min(MAX, CENTER - 20.0)),
            },
            duration_s=self.duration_s / 2,
        ),
        ServoFrame(
            targets={SERVO_LEFT_ARM: CENTER, SERVO_RIGHT_ARM: CENTER, SERVO_HEAD_TILT: CENTER},
            duration_s=self.duration_s / 2,
        ),
    ]

Greet dataclass

Bases: _BaseRequest

Source code in src/robot/body_language/requests.py
@dataclass(slots=True, frozen=True)
class Greet(_BaseRequest):
    name: str = "greet"
    duration_s: float = 0.8

    def frames(self) -> list[ServoFrame]:
        up = max(MIN, min(MAX, CENTER - 30.0))
        return [
            ServoFrame(
                targets={SERVO_RIGHT_ARM: up, SERVO_HEAD_TILT: max(MIN, min(MAX, CENTER - 10.0))},
                duration_s=self.duration_s / 3,
            ),
            ServoFrame(
                targets={SERVO_RIGHT_ARM: CENTER, SERVO_HEAD_TILT: CENTER},
                duration_s=self.duration_s / 3,
            ),
            ServoFrame(
                targets={SERVO_RIGHT_ARM: up, SERVO_HEAD_TILT: max(MIN, min(MAX, CENTER - 10.0))},
                duration_s=self.duration_s / 3,
            ),
        ]

duration_s = 0.8 class-attribute instance-attribute

name = 'greet' class-attribute instance-attribute

__init__(name='greet', duration_s=0.8)

frames()

Source code in src/robot/body_language/requests.py
def frames(self) -> list[ServoFrame]:
    up = max(MIN, min(MAX, CENTER - 30.0))
    return [
        ServoFrame(
            targets={SERVO_RIGHT_ARM: up, SERVO_HEAD_TILT: max(MIN, min(MAX, CENTER - 10.0))},
            duration_s=self.duration_s / 3,
        ),
        ServoFrame(
            targets={SERVO_RIGHT_ARM: CENTER, SERVO_HEAD_TILT: CENTER},
            duration_s=self.duration_s / 3,
        ),
        ServoFrame(
            targets={SERVO_RIGHT_ARM: up, SERVO_HEAD_TILT: max(MIN, min(MAX, CENTER - 10.0))},
            duration_s=self.duration_s / 3,
        ),
    ]

HeadNod dataclass

Bases: _BaseRequest

Source code in src/robot/body_language/requests.py
@dataclass(slots=True, frozen=True)
class HeadNod(_BaseRequest):
    name: str = "head_nod"
    amplitude: float = 15.0
    duration_s: float = 0.5

    def frames(self) -> list[ServoFrame]:
        fwd = max(MIN, min(MAX, CENTER - self.amplitude))
        return [
            ServoFrame(targets={SERVO_HEAD_TILT: fwd}, duration_s=self.duration_s / 2),
            ServoFrame(targets={SERVO_HEAD_TILT: CENTER}, duration_s=self.duration_s / 2),
        ]

amplitude = 15.0 class-attribute instance-attribute

duration_s = 0.5 class-attribute instance-attribute

name = 'head_nod' class-attribute instance-attribute

__init__(name='head_nod', amplitude=15.0, duration_s=0.5)

frames()

Source code in src/robot/body_language/requests.py
def frames(self) -> list[ServoFrame]:
    fwd = max(MIN, min(MAX, CENTER - self.amplitude))
    return [
        ServoFrame(targets={SERVO_HEAD_TILT: fwd}, duration_s=self.duration_s / 2),
        ServoFrame(targets={SERVO_HEAD_TILT: CENTER}, duration_s=self.duration_s / 2),
    ]

HeadTiltRequest dataclass

Bases: _BaseRequest

Source code in src/robot/body_language/requests.py
@dataclass(slots=True, frozen=True)
class HeadTiltRequest(_BaseRequest):
    name: str = "head_tilt"
    direction: str = "left"
    amount: float = 15.0
    duration_s: float = 0.4

    def frames(self) -> list[ServoFrame]:
        sign = -1.0 if self.direction == "left" else 1.0
        return [
            ServoFrame(
                targets={SERVO_HEAD_TILT: max(MIN, min(MAX, CENTER + sign * self.amount))},
                duration_s=self.duration_s,
            )
        ]

amount = 15.0 class-attribute instance-attribute

direction = 'left' class-attribute instance-attribute

duration_s = 0.4 class-attribute instance-attribute

name = 'head_tilt' class-attribute instance-attribute

__init__(name='head_tilt', direction='left', amount=15.0, duration_s=0.4)

frames()

Source code in src/robot/body_language/requests.py
def frames(self) -> list[ServoFrame]:
    sign = -1.0 if self.direction == "left" else 1.0
    return [
        ServoFrame(
            targets={SERVO_HEAD_TILT: max(MIN, min(MAX, CENTER + sign * self.amount))},
            duration_s=self.duration_s,
        )
    ]

LookLeft dataclass

Bases: _BaseRequest

Source code in src/robot/body_language/requests.py
@dataclass(slots=True, frozen=True)
class LookLeft(_BaseRequest):
    name: str = "look_left"
    amount: float = 30.0
    duration_s: float = 0.3

    def frames(self) -> list[ServoFrame]:
        return [
            ServoFrame(
                targets={SERVO_HEAD_PAN: max(MIN, min(MAX, CENTER - self.amount))},
                duration_s=self.duration_s,
            )
        ]

amount = 30.0 class-attribute instance-attribute

duration_s = 0.3 class-attribute instance-attribute

name = 'look_left' class-attribute instance-attribute

__init__(name='look_left', amount=30.0, duration_s=0.3)

frames()

Source code in src/robot/body_language/requests.py
def frames(self) -> list[ServoFrame]:
    return [
        ServoFrame(
            targets={SERVO_HEAD_PAN: max(MIN, min(MAX, CENTER - self.amount))},
            duration_s=self.duration_s,
        )
    ]

LookRight dataclass

Bases: _BaseRequest

Source code in src/robot/body_language/requests.py
@dataclass(slots=True, frozen=True)
class LookRight(_BaseRequest):
    name: str = "look_right"
    amount: float = 30.0
    duration_s: float = 0.3

    def frames(self) -> list[ServoFrame]:
        return [
            ServoFrame(
                targets={SERVO_HEAD_PAN: max(MIN, min(MAX, CENTER + self.amount))},
                duration_s=self.duration_s,
            )
        ]

amount = 30.0 class-attribute instance-attribute

duration_s = 0.3 class-attribute instance-attribute

name = 'look_right' class-attribute instance-attribute

__init__(name='look_right', amount=30.0, duration_s=0.3)

frames()

Source code in src/robot/body_language/requests.py
def frames(self) -> list[ServoFrame]:
    return [
        ServoFrame(
            targets={SERVO_HEAD_PAN: max(MIN, min(MAX, CENTER + self.amount))},
            duration_s=self.duration_s,
        )
    ]

ServoCalibration dataclass

Per-servo calibration (limits, centre, sign).

Source code in src/robot/body_language/requests.py
@dataclass(slots=True, frozen=True)
class ServoCalibration:
    """Per-servo calibration (limits, centre, sign)."""

    name: str
    min_angle: float
    max_angle: float
    center_angle: float
    inverted: bool = False

    def clamp(self, angle: float) -> float:
        return max(self.min_angle, min(self.max_angle, angle))

    def normalised(self, angle: float) -> float:
        """Return a value in ``[-1, 1]`` relative to the servo range."""
        half = (self.max_angle - self.min_angle) / 2.0
        if half <= 0:
            return 0.0
        mid = (self.max_angle + self.min_angle) / 2.0
        v = (angle - mid) / half
        return max(-1.0, min(1.0, v))

    def from_normalised(self, value: float) -> float:
        v = max(-1.0, min(1.0, value))
        half = (self.max_angle - self.min_angle) / 2.0
        mid = (self.max_angle + self.min_angle) / 2.0
        if self.inverted:
            v = -v
        return self.clamp(mid + v * half)

center_angle instance-attribute

inverted = False class-attribute instance-attribute

max_angle instance-attribute

min_angle instance-attribute

name instance-attribute

__init__(name, min_angle, max_angle, center_angle, inverted=False)

clamp(angle)

Source code in src/robot/body_language/requests.py
def clamp(self, angle: float) -> float:
    return max(self.min_angle, min(self.max_angle, angle))

from_normalised(value)

Source code in src/robot/body_language/requests.py
def from_normalised(self, value: float) -> float:
    v = max(-1.0, min(1.0, value))
    half = (self.max_angle - self.min_angle) / 2.0
    mid = (self.max_angle + self.min_angle) / 2.0
    if self.inverted:
        v = -v
    return self.clamp(mid + v * half)

normalised(angle)

Return a value in [-1, 1] relative to the servo range.

Source code in src/robot/body_language/requests.py
def normalised(self, angle: float) -> float:
    """Return a value in ``[-1, 1]`` relative to the servo range."""
    half = (self.max_angle - self.min_angle) / 2.0
    if half <= 0:
        return 0.0
    mid = (self.max_angle + self.min_angle) / 2.0
    v = (angle - mid) / half
    return max(-1.0, min(1.0, v))

ServoFrame dataclass

A target angle for every named servo at one instant.

Source code in src/robot/body_language/requests.py
@dataclass(slots=True, frozen=True)
class ServoFrame:
    """A target angle for every named servo at one instant."""

    targets: dict[str, float] = field(default_factory=dict)
    duration_s: float = 0.4

    def get(self, name: str, default: float) -> float:
        return self.targets.get(name, default)

duration_s = 0.4 class-attribute instance-attribute

targets = field(default_factory=dict) class-attribute instance-attribute

__init__(targets=dict(), duration_s=0.4)

get(name, default)

Source code in src/robot/body_language/requests.py
def get(self, name: str, default: float) -> float:
    return self.targets.get(name, default)

Shrug dataclass

Bases: _BaseRequest

Source code in src/robot/body_language/requests.py
@dataclass(slots=True, frozen=True)
class Shrug(_BaseRequest):
    name: str = "shrug"
    duration_s: float = 0.5

    def frames(self) -> list[ServoFrame]:
        up = max(MIN, min(MAX, CENTER - 30.0))
        return [
            ServoFrame(
                targets={
                    SERVO_LEFT_ARM: up,
                    SERVO_RIGHT_ARM: up,
                    SERVO_HEAD_TILT: max(MIN, min(MAX, CENTER - 10.0)),
                },
                duration_s=self.duration_s,
            )
        ]

duration_s = 0.5 class-attribute instance-attribute

name = 'shrug' class-attribute instance-attribute

__init__(name='shrug', duration_s=0.5)

frames()

Source code in src/robot/body_language/requests.py
def frames(self) -> list[ServoFrame]:
    up = max(MIN, min(MAX, CENTER - 30.0))
    return [
        ServoFrame(
            targets={
                SERVO_LEFT_ARM: up,
                SERVO_RIGHT_ARM: up,
                SERVO_HEAD_TILT: max(MIN, min(MAX, CENTER - 10.0)),
            },
            duration_s=self.duration_s,
        )
    ]

Wave dataclass

Bases: _BaseRequest

Source code in src/robot/body_language/requests.py
@dataclass(slots=True, frozen=True)
class Wave(_BaseRequest):
    name: str = "wave"
    amplitude: float = 30.0
    duration_s: float = 1.0

    def frames(self) -> list[ServoFrame]:
        up = max(MIN, min(MAX, CENTER - self.amplitude))
        return [
            ServoFrame(targets={SERVO_RIGHT_ARM: up}, duration_s=self.duration_s / 4),
            ServoFrame(targets={SERVO_RIGHT_ARM: CENTER}, duration_s=self.duration_s / 4),
            ServoFrame(targets={SERVO_RIGHT_ARM: up}, duration_s=self.duration_s / 4),
            ServoFrame(targets={SERVO_RIGHT_ARM: CENTER}, duration_s=self.duration_s / 4),
        ]

amplitude = 30.0 class-attribute instance-attribute

duration_s = 1.0 class-attribute instance-attribute

name = 'wave' class-attribute instance-attribute

__init__(name='wave', amplitude=30.0, duration_s=1.0)

frames()

Source code in src/robot/body_language/requests.py
def frames(self) -> list[ServoFrame]:
    up = max(MIN, min(MAX, CENTER - self.amplitude))
    return [
        ServoFrame(targets={SERVO_RIGHT_ARM: up}, duration_s=self.duration_s / 4),
        ServoFrame(targets={SERVO_RIGHT_ARM: CENTER}, duration_s=self.duration_s / 4),
        ServoFrame(targets={SERVO_RIGHT_ARM: up}, duration_s=self.duration_s / 4),
        ServoFrame(targets={SERVO_RIGHT_ARM: CENTER}, duration_s=self.duration_s / 4),
    ]

_BaseRequest dataclass

Source code in src/robot/body_language/requests.py
@dataclass(slots=True, frozen=True)
class _BaseRequest:
    name: str

    def frames(self) -> list[ServoFrame]:
        return []

name instance-attribute

__init__(name)

frames()

Source code in src/robot/body_language/requests.py
def frames(self) -> list[ServoFrame]:
    return []

_arms(center, left, right, dur=0.4)

Source code in src/robot/body_language/requests.py
def _arms(center: float, left: float, right: float, dur: float = 0.4) -> ServoFrame:
    return ServoFrame(
        targets={
            SERVO_LEFT_ARM: center + (left - center) * 0.5,
            SERVO_RIGHT_ARM: center + (right - center) * 0.5,
        },
        duration_s=dur,
    )

_head(center, pan, tilt, dur=0.4)

Source code in src/robot/body_language/requests.py
def _head(center: float, pan: float, tilt: float, dur: float = 0.4) -> ServoFrame:
    return ServoFrame(
        targets={
            SERVO_HEAD_PAN: center + (pan - center) * 0.5,
            SERVO_HEAD_TILT: center + (tilt - center) * 0.5,
        },
        duration_s=dur,
    )

Engine

robot.body_language.engine

The :class:BodyLanguageEngine - plays body-language requests on the servos.

The engine owns the :class:ServoController and a per-servo :class:ServoCalibration. To perform a request it:

  1. Asks the request for a list of :class:ServoFrame objects.
  2. Plays each frame sequentially, interpolating every servo's angle over the frame's duration_s with a smoothstep easing.
  3. Returns the new angles so the simulation overlay can read them.

DEFAULT_CALIBRATION = {SERVO_HEAD_PAN: ServoCalibration(SERVO_HEAD_PAN, 30.0, 150.0, 90.0), SERVO_HEAD_TILT: ServoCalibration(SERVO_HEAD_TILT, 45.0, 135.0, 90.0), SERVO_LEFT_ARM: ServoCalibration(SERVO_LEFT_ARM, 20.0, 160.0, 90.0), SERVO_RIGHT_ARM: ServoCalibration(SERVO_RIGHT_ARM, 20.0, 160.0, 90.0)} module-attribute

__all__ = ['BodyLanguageEngine', 'Pose', 'hint_to_pose'] module-attribute

_log = get_logger('body_language.engine') module-attribute

ArmPose

Bases: Enum

Discrete arm-pose hints.

Source code in src/robot/face/model.py
class ArmPose(Enum):
    """Discrete arm-pose hints."""

    RELAXED = "relaxed"
    OPEN = "open"  # slightly raised
    WIDE = "wide"  # celebration
    WAVING = "waving"  # one arm up
    SHRUG = "shrug"  # both up
    DOWN = "down"  # rest
    POINT = "point"  # one arm forward

DOWN = 'down' class-attribute instance-attribute

OPEN = 'open' class-attribute instance-attribute

POINT = 'point' class-attribute instance-attribute

RELAXED = 'relaxed' class-attribute instance-attribute

SHRUG = 'shrug' class-attribute instance-attribute

WAVING = 'waving' class-attribute instance-attribute

WIDE = 'wide' class-attribute instance-attribute

BodyLanguageEngine dataclass

Drive the four servos with high-level body-language requests.

Source code in src/robot/body_language/engine.py
@dataclass(slots=True)
class BodyLanguageEngine:
    """Drive the four servos with high-level body-language requests."""

    servo_controller: ServoController
    clock: Clock
    calibration: dict[str, ServoCalibration] = field(
        default_factory=lambda: dict(DEFAULT_CALIBRATION)
    )

    _current: Pose = field(default_factory=Pose, init=False)
    _busy: bool = field(default=False, init=False)

    def set_calibration(self, calibration: dict[str, ServoCalibration]) -> None:
        self.calibration = calibration

    def snapshot(self) -> Pose:
        """Current pose - used by the simulation overlay."""
        return self._current

    def apply_hint(self, hint: object) -> Pose:
        """Translate a :class:`BodyLanguageHint` into a Pose (no servo moves)."""
        pose = hint_to_pose(hint)
        self._current = pose
        return pose

    async def perform(self, request: BodyRequest) -> None:
        """Play a request on the servos."""
        if self._busy:
            # Another request is already in flight - log the dropped request
            # so it's visible rather than silently lost.
            _log.warning(
                "body_language.request_dropped", request=getattr(request, "name", "unknown")
            )
            return
        self._busy = True
        try:
            for frame in request.frames():
                await self._play_frame(frame)
        finally:
            self._busy = False

    def perform_sync(self, request: BodyRequest) -> None:
        """Synchronous version (for tests and the simulation CLI)."""
        for frame in request.frames():
            self._play_frame_sync(frame)

    async def play_frames(self, frames: Iterable[ServoFrame]) -> None:
        async for _ in self._aiter_frames(frames):
            pass

    async def _aiter_frames(self, frames: Iterable[ServoFrame]) -> AsyncIterator[None]:
        for frame in frames:
            await self._play_frame(frame)
            yield

    async def _play_frame(self, frame: ServoFrame) -> None:
        if not frame.targets:
            await self.clock.sleep(frame.duration_s)
            return
        # Compute the per-servo interpolation start positions
        start_targets = {name: self._current.get(name, 90.0) for name in frame.targets}
        steps = max(1, int(frame.duration_s * 30))
        step_s = frame.duration_s / steps
        for step in range(1, steps + 1):
            t = step / steps
            eased = t * t * (3.0 - 2.0 * t)
            targets: dict[str, float] = {}
            for name, target in frame.targets.items():
                start = start_targets[name]
                targets[name] = self._calibrate(name, start + (target - start) * eased)
            # Apply every servo in this slice
            await self._apply_targets(targets)
            self._current = Pose(targets={**self._current.targets, **targets})
            await self.clock.sleep(step_s)

    def _play_frame_sync(self, frame: ServoFrame) -> None:
        if not frame.targets:
            return
        # Apply each servo's calibrated target directly (sync mode jumps
        # to the target without interpolation).
        new_targets = dict(self._current.targets)
        for name, target in frame.targets.items():
            calibrated = self._calibrate(name, target)
            new_targets[name] = calibrated
        self._current = Pose(targets=new_targets)

    async def _apply_targets(self, targets: dict[str, float]) -> None:
        for name, angle in targets.items():
            servo = self._get_servo(name)
            if servo is not None:
                with contextlib.suppress(Exception):
                    await servo.move_to(angle, duration_s=0.0)

    def _apply_targets_sync(self, targets: dict[str, float]) -> None:
        for name, angle in targets.items():
            servo = self._get_servo(name)
            if servo is not None:
                # The sync method is used by the simulator CLI and the tests.
                # It updates the snapshot but does not call the async
                # ``servo.move_to`` (that would require a running loop).
                self._current = Pose(
                    targets={**self._current.targets, name: self._calibrate(name, angle)}
                )

    def _get_servo(self, name: str) -> Servo | None:
        try:
            return self.servo_controller.get(name)
        except Exception:
            return None

    def _calibrate(self, name: str, angle: float) -> float:
        cal = self.calibration.get(name)
        if cal is None:
            return max(0.0, min(180.0, angle))
        return cal.clamp(angle)

calibration = field(default_factory=lambda: dict(DEFAULT_CALIBRATION)) class-attribute instance-attribute

clock instance-attribute

servo_controller instance-attribute

__init__(servo_controller, clock, calibration=(lambda: dict(DEFAULT_CALIBRATION))())

apply_hint(hint)

Translate a :class:BodyLanguageHint into a Pose (no servo moves).

Source code in src/robot/body_language/engine.py
def apply_hint(self, hint: object) -> Pose:
    """Translate a :class:`BodyLanguageHint` into a Pose (no servo moves)."""
    pose = hint_to_pose(hint)
    self._current = pose
    return pose

perform(request) async

Play a request on the servos.

Source code in src/robot/body_language/engine.py
async def perform(self, request: BodyRequest) -> None:
    """Play a request on the servos."""
    if self._busy:
        # Another request is already in flight - log the dropped request
        # so it's visible rather than silently lost.
        _log.warning(
            "body_language.request_dropped", request=getattr(request, "name", "unknown")
        )
        return
    self._busy = True
    try:
        for frame in request.frames():
            await self._play_frame(frame)
    finally:
        self._busy = False

perform_sync(request)

Synchronous version (for tests and the simulation CLI).

Source code in src/robot/body_language/engine.py
def perform_sync(self, request: BodyRequest) -> None:
    """Synchronous version (for tests and the simulation CLI)."""
    for frame in request.frames():
        self._play_frame_sync(frame)

play_frames(frames) async

Source code in src/robot/body_language/engine.py
async def play_frames(self, frames: Iterable[ServoFrame]) -> None:
    async for _ in self._aiter_frames(frames):
        pass

set_calibration(calibration)

Source code in src/robot/body_language/engine.py
def set_calibration(self, calibration: dict[str, ServoCalibration]) -> None:
    self.calibration = calibration

snapshot()

Current pose - used by the simulation overlay.

Source code in src/robot/body_language/engine.py
def snapshot(self) -> Pose:
    """Current pose - used by the simulation overlay."""
    return self._current

BodyRequest

Bases: Protocol

A high-level body-language request.

Source code in src/robot/body_language/requests.py
@runtime_checkable
class BodyRequest(Protocol):
    """A high-level body-language request."""

    @property
    def name(self) -> str: ...

    def frames(self) -> list[ServoFrame]: ...

name property

frames()

Source code in src/robot/body_language/requests.py
def frames(self) -> list[ServoFrame]: ...

Clock

Bases: Protocol

Minimal time abstraction.

Source code in src/robot/utils/clock.py
class Clock(Protocol):
    """Minimal time abstraction."""

    def now(self) -> datetime:
        """Return the current wall-clock time (UTC)."""

    def monotonic(self) -> float:
        """Return a strictly monotonic time in seconds."""

    async def sleep(self, seconds: float) -> None:
        """Sleep for the given number of seconds."""

monotonic()

Return a strictly monotonic time in seconds.

Source code in src/robot/utils/clock.py
def monotonic(self) -> float:
    """Return a strictly monotonic time in seconds."""

now()

Return the current wall-clock time (UTC).

Source code in src/robot/utils/clock.py
def now(self) -> datetime:
    """Return the current wall-clock time (UTC)."""

sleep(seconds) async

Sleep for the given number of seconds.

Source code in src/robot/utils/clock.py
async def sleep(self, seconds: float) -> None:
    """Sleep for the given number of seconds."""

HeadTilt

Bases: Enum

Discrete head-tilt hints the body-language engine understands.

Source code in src/robot/face/model.py
class HeadTilt(Enum):
    """Discrete head-tilt hints the body-language engine understands."""

    NEUTRAL = "neutral"
    CURIOUS = "curious"  # slight tilt
    THINKING = "thinking"  # small side-to-side nod
    SLEEPY = "sleepy"  # droop
    SAD = "sad"  # downward
    EXCITED = "excited"  # quick tilt

CURIOUS = 'curious' class-attribute instance-attribute

EXCITED = 'excited' class-attribute instance-attribute

NEUTRAL = 'neutral' class-attribute instance-attribute

SAD = 'sad' class-attribute instance-attribute

SLEEPY = 'sleepy' class-attribute instance-attribute

THINKING = 'thinking' class-attribute instance-attribute

Pose dataclass

A snapshot of every servo's target angle.

Source code in src/robot/body_language/engine.py
@dataclass(slots=True, frozen=True)
class Pose:
    """A snapshot of every servo's target angle."""

    targets: dict[str, float] = field(default_factory=dict)

    def get(self, name: str, default: float = 90.0) -> float:
        return self.targets.get(name, default)

targets = field(default_factory=dict) class-attribute instance-attribute

__init__(targets=dict())

get(name, default=90.0)

Source code in src/robot/body_language/engine.py
def get(self, name: str, default: float = 90.0) -> float:
    return self.targets.get(name, default)

Servo

Bases: Protocol

A single addressable servo channel.

Source code in src/robot/interfaces/servo.py
@runtime_checkable
class Servo(Protocol):
    """A single addressable servo channel."""

    @property
    def name(self) -> str:
        """Logical name of the servo (e.g. ``"head_pan"``)."""

    @property
    def angle(self) -> float:
        """Current angle in degrees."""

    async def move_to(self, angle: float, duration_s: float = 0.4) -> None:
        """Move to the target angle over ``duration_s`` seconds."""

    async def release(self) -> None:
        """Stop driving the servo (relax PWM)."""

angle property

Current angle in degrees.

name property

Logical name of the servo (e.g. "head_pan").

move_to(angle, duration_s=0.4) async

Move to the target angle over duration_s seconds.

Source code in src/robot/interfaces/servo.py
async def move_to(self, angle: float, duration_s: float = 0.4) -> None:
    """Move to the target angle over ``duration_s`` seconds."""

release() async

Stop driving the servo (relax PWM).

Source code in src/robot/interfaces/servo.py
async def release(self) -> None:
    """Stop driving the servo (relax PWM)."""

ServoCalibration dataclass

Per-servo calibration (limits, centre, sign).

Source code in src/robot/body_language/requests.py
@dataclass(slots=True, frozen=True)
class ServoCalibration:
    """Per-servo calibration (limits, centre, sign)."""

    name: str
    min_angle: float
    max_angle: float
    center_angle: float
    inverted: bool = False

    def clamp(self, angle: float) -> float:
        return max(self.min_angle, min(self.max_angle, angle))

    def normalised(self, angle: float) -> float:
        """Return a value in ``[-1, 1]`` relative to the servo range."""
        half = (self.max_angle - self.min_angle) / 2.0
        if half <= 0:
            return 0.0
        mid = (self.max_angle + self.min_angle) / 2.0
        v = (angle - mid) / half
        return max(-1.0, min(1.0, v))

    def from_normalised(self, value: float) -> float:
        v = max(-1.0, min(1.0, value))
        half = (self.max_angle - self.min_angle) / 2.0
        mid = (self.max_angle + self.min_angle) / 2.0
        if self.inverted:
            v = -v
        return self.clamp(mid + v * half)

center_angle instance-attribute

inverted = False class-attribute instance-attribute

max_angle instance-attribute

min_angle instance-attribute

name instance-attribute

__init__(name, min_angle, max_angle, center_angle, inverted=False)

clamp(angle)

Source code in src/robot/body_language/requests.py
def clamp(self, angle: float) -> float:
    return max(self.min_angle, min(self.max_angle, angle))

from_normalised(value)

Source code in src/robot/body_language/requests.py
def from_normalised(self, value: float) -> float:
    v = max(-1.0, min(1.0, value))
    half = (self.max_angle - self.min_angle) / 2.0
    mid = (self.max_angle + self.min_angle) / 2.0
    if self.inverted:
        v = -v
    return self.clamp(mid + v * half)

normalised(angle)

Return a value in [-1, 1] relative to the servo range.

Source code in src/robot/body_language/requests.py
def normalised(self, angle: float) -> float:
    """Return a value in ``[-1, 1]`` relative to the servo range."""
    half = (self.max_angle - self.min_angle) / 2.0
    if half <= 0:
        return 0.0
    mid = (self.max_angle + self.min_angle) / 2.0
    v = (angle - mid) / half
    return max(-1.0, min(1.0, v))

ServoController

Bases: Protocol

A controller that owns a collection of :class:Servo channels.

A controller is selected at application boot by the :class:~robot.hardware.servos.factory.ServoControllerFactory based on the value of config.servo.backend. The rest of the application only ever depends on this interface.

Source code in src/robot/interfaces/servo.py
@runtime_checkable
class ServoController(Protocol):
    """A controller that owns a collection of :class:`Servo` channels.

    A controller is selected at application boot by the
    :class:`~robot.hardware.servos.factory.ServoControllerFactory` based on
    the value of ``config.servo.backend``. The rest of the application only
    ever depends on this interface.
    """

    @property
    def backend_name(self) -> str:
        """Human-readable backend identifier (e.g. ``"gpio"``, ``"pca9685"``)."""

    def get(self, name: str) -> Servo:
        """Return the :class:`Servo` registered under ``name``."""

    def all(self) -> list[Servo]:
        """Return every :class:`Servo` known to this controller."""

    async def release_all(self) -> None:
        """Relax every servo (PWM goes to 0)."""

    async def close(self) -> None:
        """Release hardware resources; safe to call multiple times."""

backend_name property

Human-readable backend identifier (e.g. "gpio", "pca9685").

all()

Return every :class:Servo known to this controller.

Source code in src/robot/interfaces/servo.py
def all(self) -> list[Servo]:
    """Return every :class:`Servo` known to this controller."""

close() async

Release hardware resources; safe to call multiple times.

Source code in src/robot/interfaces/servo.py
async def close(self) -> None:
    """Release hardware resources; safe to call multiple times."""

get(name)

Return the :class:Servo registered under name.

Source code in src/robot/interfaces/servo.py
def get(self, name: str) -> Servo:
    """Return the :class:`Servo` registered under ``name``."""

release_all() async

Relax every servo (PWM goes to 0).

Source code in src/robot/interfaces/servo.py
async def release_all(self) -> None:
    """Relax every servo (PWM goes to 0)."""

ServoFrame dataclass

A target angle for every named servo at one instant.

Source code in src/robot/body_language/requests.py
@dataclass(slots=True, frozen=True)
class ServoFrame:
    """A target angle for every named servo at one instant."""

    targets: dict[str, float] = field(default_factory=dict)
    duration_s: float = 0.4

    def get(self, name: str, default: float) -> float:
        return self.targets.get(name, default)

duration_s = 0.4 class-attribute instance-attribute

targets = field(default_factory=dict) class-attribute instance-attribute

__init__(targets=dict(), duration_s=0.4)

get(name, default)

Source code in src/robot/body_language/requests.py
def get(self, name: str, default: float) -> float:
    return self.targets.get(name, default)

get_logger(name)

Return a bound logger for the given module name.

The name is prefixed with robot. if it doesn't already start with it, so log records naturally form a hierarchy. The name is also bound into the event context as logger_name so :func:_capture_to_ring_buffer can record it; :func:_strip_logger_name removes it before rendering so the stdout JSON output stays unchanged.

Source code in src/robot/logging.py
def get_logger(name: str) -> structlog.stdlib.BoundLogger:
    """Return a bound logger for the given module name.

    The name is prefixed with ``robot.`` if it doesn't already start with it,
    so log records naturally form a hierarchy. The name is also bound into
    the event context as ``logger_name`` so :func:`_capture_to_ring_buffer`
    can record it; :func:`_strip_logger_name` removes it before rendering so
    the stdout JSON output stays unchanged.
    """
    if not name.startswith("robot."):
        name = f"robot.{name}"
    logger = structlog.get_logger(name).bind(logger_name=name)
    return cast("structlog.stdlib.BoundLogger", logger)

hint_to_pose(hint)

Translate a :class:BodyLanguageHint into a static :class:Pose.

The result represents a resting pose - the body-language engine applies it as a base, and transient requests (Wave, Celebrate, …) layer on top.

Source code in src/robot/body_language/engine.py
def hint_to_pose(hint: object) -> Pose:  # noqa: PLR0912
    """Translate a :class:`BodyLanguageHint` into a static :class:`Pose`.

    The result represents a *resting* pose - the body-language engine
    applies it as a base, and transient requests (Wave, Celebrate, …)
    layer on top.
    """

    head_tilt: HeadTilt = getattr(hint, "head_tilt", HeadTilt.NEUTRAL)
    arm_pose: ArmPose = getattr(hint, "arm_pose", ArmPose.RELAXED)
    intensity: float = float(getattr(hint, "intensity", 1.0))

    head_targets: dict[str, float] = {
        "pan": 90.0,
        "tilt": 90.0,
    }
    arm_targets: dict[str, float] = {
        "left_arm": 90.0,
        "right_arm": 90.0,
    }

    # Head tilt mapping
    if head_tilt is HeadTilt.CURIOUS:
        head_targets["tilt"] = 90.0 - 15.0 * intensity
        head_targets["pan"] = 90.0 - 10.0 * intensity
    elif head_tilt is HeadTilt.THINKING:
        head_targets["tilt"] = 90.0 - 5.0 * intensity
        head_targets["pan"] = 90.0 - 5.0 * intensity
    elif head_tilt is HeadTilt.SLEEPY:
        head_targets["tilt"] = 90.0 + 25.0 * intensity
    elif head_tilt is HeadTilt.SAD:
        head_targets["tilt"] = 90.0 + 20.0 * intensity
        head_targets["pan"] = 90.0
    elif head_tilt is HeadTilt.EXCITED:
        head_targets["tilt"] = 90.0 - 10.0 * intensity
        head_targets["pan"] = 90.0
    else:
        head_targets["tilt"] = 90.0
        head_targets["pan"] = 90.0

    # Arm pose mapping
    if arm_pose is ArmPose.OPEN:
        arm_targets["left_arm"] = 90.0 - 20.0 * intensity
        arm_targets["right_arm"] = 90.0 + 20.0 * intensity
    elif arm_pose is ArmPose.WIDE:
        arm_targets["left_arm"] = 90.0 - 45.0 * intensity
        arm_targets["right_arm"] = 90.0 + 45.0 * intensity
    elif arm_pose is ArmPose.WAVING:
        arm_targets["right_arm"] = 90.0 - 30.0 * intensity
        arm_targets["left_arm"] = 90.0
    elif arm_pose is ArmPose.SHRUG:
        arm_targets["left_arm"] = 90.0 - 30.0 * intensity
        arm_targets["right_arm"] = 90.0 - 30.0 * intensity
        head_targets["tilt"] = 90.0 - 10.0 * intensity
    elif arm_pose is ArmPose.DOWN:
        arm_targets["left_arm"] = 90.0 + 20.0 * intensity
        arm_targets["right_arm"] = 90.0 + 20.0 * intensity
    elif arm_pose is ArmPose.POINT:
        arm_targets["right_arm"] = 90.0 - 30.0 * intensity
    else:  # RELAXED
        arm_targets["left_arm"] = 90.0
        arm_targets["right_arm"] = 90.0

    return Pose(targets={**head_targets, **arm_targets})