refactor: styles own their ringing tone directly (Pattern C)

Drop the injected AlarmSound Protocol and the wecker.Sound class. Each style
now owns its tone by using pygame directly; the runner owns only the audio
engine lifecycle (mixer init/quit), button sampling, and cleanup. This is the
seam for future styles that handle their own tone — a 'talk' style would just
import pygame and play speech, with no shared interface to extend.

- styles/base.py: AlarmStyle.__init__(set_led, music_file) + start() + update()
- styles/blink.py: start() loads+plays music via pygame.mixer.music
- styles/simple.py: owns its beep — synthesises a square-wave buffer in
  module (stdlib array+math) and plays it via pygame.mixer.Sound
- wecker.py: setup() brings up the mixer only; run_alarm constructs the style
  and guards start() with a clean log+exit on failure

Tests: a shared tests/conftest.py stubs RPi.GPIO/pygame in sys.modules before
any SUT import (order-independent, removes duplicated inline mocking); the
wecker mock_pygame fixture patches one fresh pygame mock into wecker + both
style modules so assertions see the same calls.

README: tone-ownership and plugin-contract updated.
This commit is contained in:
2026-08-02 21:50:00 +02:00
parent 92eba762ce
commit 3a7b6ac7a3
10 changed files with 167 additions and 190 deletions
+11 -29
View File
@@ -1,44 +1,26 @@
from abc import ABC, abstractmethod
from typing import Callable, Protocol
class AlarmSound(Protocol):
"""Audio capability injected into a style so it can own its ringing tone.
Styles stay free of pygame/GPIO imports (the API process imports them only
for name validation); the runner supplies a concrete implementation.
"""
def play_music(self, path: str) -> None:
"""Load and play a music file on an endless loop."""
...
def play_beep(self) -> None:
"""Play one short beep tone."""
...
from typing import Callable
class AlarmStyle(ABC):
"""A pluggable alarm behaviour.
A style owns *its own ringing tone* (via the injected ``sound``) and
decides when the alarm stops and what the LED does. It never touches
hardware directly: ``set_led`` and ``sound`` are injected by the runner, so
styles stay import-safe in the API process (no GPIO/pygame).
A style owns *its own ringing tone*: it uses the audio engine (pygame)
directly and decides when the alarm stops and what the LED does. It never
touches hardware directly: ``set_led`` is injected by the runner, and the
runner owns the audio engine lifecycle (mixer init/quit). Styles stay
import-safe in the API process — ``import pygame`` does not initialise
audio, so the API can import styles just to validate names.
Lifecycle: construct once with ``set_led``/``sound``/``music_file``; call
``start()`` to begin ringing (kick off the tone and initial LED); then call
``update`` every tick. Return ``False`` from ``update`` to stop the alarm.
Lifecycle: construct once with ``set_led``/``music_file``; call ``start()``
to begin ringing (kick off the tone and initial LED); then call ``update``
every tick. Return ``False`` from ``update`` to stop the alarm.
"""
def __init__(
self,
set_led: Callable[[bool], None],
sound: AlarmSound,
music_file: str | None = None,
self, set_led: Callable[[bool], None], music_file: str | None = None
):
self.set_led = set_led
self.sound = sound
self.music_file = music_file
def start(self) -> None:
+9 -11
View File
@@ -1,6 +1,8 @@
import logging
import random
import pygame
from styles.base import AlarmStyle
# State Machine states for the puzzle flow.
@@ -21,8 +23,8 @@ class BlinkStyle(AlarmStyle):
exactly that many times. A wrong count starts a fresh sequence.
"""
def __init__(self, set_led, sound, music_file=None):
super().__init__(set_led, sound, music_file)
def __init__(self, set_led, music_file=None):
super().__init__(set_led, music_file)
self.state = STATE_RINGING
self.target_blinks = 0
self.user_presses = 0
@@ -35,7 +37,9 @@ class BlinkStyle(AlarmStyle):
def start(self):
# The puzzle rings with music on an endless loop; the LED stays off
# until the button is pressed to start the blink sequence.
self.sound.play_music(self.music_file)
pygame.mixer.music.load(self.music_file)
pygame.mixer.music.set_volume(1.0)
pygame.mixer.music.play(-1)
self.set_led(False)
def update(self, now, is_pressed):
@@ -130,14 +134,8 @@ class BlinkStyle(AlarmStyle):
if __name__ == "__main__":
# Self-check: a correct blink sequence stops the alarm.
class _StubSound:
def play_music(self, path):
pass
def play_beep(self):
pass
style = BlinkStyle(lambda on: None, _StubSound(), "x.mp3")
# (Does not call start(), which needs the audio engine.)
style = BlinkStyle(lambda on: None, "x.mp3")
assert style.update(100.0, True) is True
assert style.state == STATE_WAIT_BEFORE_BLINK
+47 -17
View File
@@ -1,3 +1,8 @@
import array
import math
import pygame
from styles.base import AlarmStyle
# Time between beep retriggers; a short beep followed by this gap gives the
@@ -5,48 +10,73 @@ from styles.base import AlarmStyle
BEEP_INTERVAL = 0.5
def _make_beep_buffer(
freq: int = 1000, duration: float = 0.15, rate: int = 44100
) -> bytes:
"""Synthesize a short square-wave beep as signed-16-bit stereo PCM.
Matches the mixer format used by wecker.setup() (rate, -16, 2 channels) so
it feeds straight into ``pygame.mixer.Sound``. No audio file, no extra dep.
"""
n = int(rate * duration)
buf = array.array("h")
for i in range(n):
v = 32767 if math.sin(2 * math.pi * freq * (i / rate)) >= 0 else -32767
buf.append(v)
buf.append(v) # duplicate to stereo
return buf.tobytes()
_BEEP_BUFFER = _make_beep_buffer()
class SimpleStyle(AlarmStyle):
"""Press the button once to stop. Rings with a repeating beep.
This style plays no music file; it owns its tone via ``sound.play_beep``.
This style plays no music file; it owns its tone via a synthesised square
wave played through ``pygame.mixer.Sound``.
"""
def __init__(self, set_led, sound, music_file=None):
super().__init__(set_led, sound, music_file)
def __init__(self, set_led, music_file=None):
super().__init__(set_led, music_file)
self._next_beep = 0.0
self._beep = None
def start(self):
# LED solid on so the button is findable in the dark.
self.set_led(True)
self._beep = pygame.mixer.Sound(_BEEP_BUFFER)
def update(self, now, is_pressed):
self.set_led(True)
if now >= self._next_beep:
self.sound.play_beep()
self._beep.play()
self._next_beep = now + BEEP_INTERVAL
return not is_pressed # first press -> False -> stop
if __name__ == "__main__":
# Self-check: not pressed keeps ringing and beeps; a press stops it.
class _StubSound:
# Self-check: the timer beeps on the interval and a press stops it.
# Bypasses start() (which needs the audio engine) by stubbing the beep.
class _Beep:
def __init__(self):
self.beeps = 0
self.plays = 0
def play_music(self, path):
raise AssertionError("simple style must never play music")
def play(self):
self.plays += 1
def play_beep(self):
self.beeps += 1
style = SimpleStyle(lambda on: None)
style._beep = _Beep()
sound = _StubSound()
style = SimpleStyle(lambda on: None, sound)
style.start()
assert style.update(0.0, False) is True
assert sound.beeps == 1 # first tick beeps
assert style._beep.plays == 1 # first tick beeps
assert style.update(0.4, False) is True # before interval -> no beep
assert sound.beeps == 1
assert style._beep.plays == 1
assert style.update(0.5, False) is True # at interval -> beep
assert sound.beeps == 2
assert style._beep.plays == 2
assert style.update(0.6, True) is False # press -> stop
print("simple self-check ok")