feat: styles own their ringing tone (simple beeps, blink plays music)

Move audio ownership out of the shared runner and into each style via an
injected Sound capability (play_music(path) / play_beep()). The runner now
only owns button sampling and cleanup; the style kicks off its own tone in
start() and drives the LED.

- simple: a repeating square-wave beep (ordinary alarm-clock tone), no music
  file required. The beep is synthesised in memory as signed-16-bit stereo
  PCM (stdlib array+math) and played via pygame.mixer.Sound — no shipped
  audio asset, no new dependency.
- blink: unchanged behaviour — music on an endless loop from --music-file /
  MUSIC_FILE / the default track, via pygame.mixer.music.
- AlarmStyle contract gains sound + music_file in __init__ and a start()
  lifecycle hook; AlarmSound Protocol documents the audio seam for future
  styles that handle their own tone.
- setup() no longer loads music (that is the style's job now).

README updated: per-style ringing tone, the --music-file note (blink only),
and the extended plugin contract.
This commit is contained in:
2026-08-02 16:29:40 +02:00
parent 88a57dab6e
commit 92eba762ce
8 changed files with 291 additions and 87 deletions
+35 -7
View File
@@ -1,20 +1,48 @@
from abc import ABC, abstractmethod
from typing import Callable
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."""
...
class AlarmStyle(ABC):
"""A pluggable alarm behaviour.
A style decides *when* the alarm stops and what the LED does while it
rings. It never touches hardware directly: ``set_led`` is injected by the
runner, so styles stay import-safe in the API process (no GPIO/pygame).
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).
Lifecycle: construct once with ``set_led``, then call ``update`` every
tick. Return ``False`` from ``update`` to stop the alarm.
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.
"""
def __init__(self, set_led: Callable[[bool], None]):
def __init__(
self,
set_led: Callable[[bool], None],
sound: AlarmSound,
music_file: str | None = None,
):
self.set_led = set_led
self.sound = sound
self.music_file = music_file
def start(self) -> None:
"""Begin ringing. Override to start the style's tone / initial LED."""
@abstractmethod
def update(self, now: float, is_pressed: bool) -> bool:
+16 -3
View File
@@ -21,8 +21,8 @@ class BlinkStyle(AlarmStyle):
exactly that many times. A wrong count starts a fresh sequence.
"""
def __init__(self, set_led):
super().__init__(set_led)
def __init__(self, set_led, sound, music_file=None):
super().__init__(set_led, sound, music_file)
self.state = STATE_RINGING
self.target_blinks = 0
self.user_presses = 0
@@ -32,6 +32,12 @@ class BlinkStyle(AlarmStyle):
self._blink_phases = 0
self._blink_next_toggle: float | None = None
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)
self.set_led(False)
def update(self, now, is_pressed):
button_just_pressed = False
if is_pressed and not self.button_was_pressed:
@@ -124,7 +130,14 @@ class BlinkStyle(AlarmStyle):
if __name__ == "__main__":
# Self-check: a correct blink sequence stops the alarm.
style = BlinkStyle(lambda on: None)
class _StubSound:
def play_music(self, path):
pass
def play_beep(self):
pass
style = BlinkStyle(lambda on: None, _StubSound(), "x.mp3")
assert style.update(100.0, True) is True
assert style.state == STATE_WAIT_BEFORE_BLINK
+39 -5
View File
@@ -1,18 +1,52 @@
from styles.base import AlarmStyle
# Time between beep retriggers; a short beep followed by this gap gives the
# classic alarm-clock "beep ... beep ... beep".
BEEP_INTERVAL = 0.5
class SimpleStyle(AlarmStyle):
"""Press the button once to stop the alarm."""
"""Press the button once to stop. Rings with a repeating beep.
def update(self, now, is_pressed):
This style plays no music file; it owns its tone via ``sound.play_beep``.
"""
def __init__(self, set_led, sound, music_file=None):
super().__init__(set_led, sound, music_file)
self._next_beep = 0.0
def start(self):
# LED solid on so the button is findable in the dark.
self.set_led(True)
def update(self, now, is_pressed):
self.set_led(True)
if now >= self._next_beep:
self.sound.play_beep()
self._next_beep = now + BEEP_INTERVAL
return not is_pressed # first press -> False -> stop
if __name__ == "__main__":
# Self-check: not pressed keeps ringing; a press stops it.
style = SimpleStyle(lambda on: None)
# Self-check: not pressed keeps ringing and beeps; a press stops it.
class _StubSound:
def __init__(self):
self.beeps = 0
def play_music(self, path):
raise AssertionError("simple style must never play music")
def play_beep(self):
self.beeps += 1
sound = _StubSound()
style = SimpleStyle(lambda on: None, sound)
style.start()
assert style.update(0.0, False) is True
assert style.update(0.1, True) is False
assert sound.beeps == 1 # first tick beeps
assert style.update(0.4, False) is True # before interval -> no beep
assert sound.beeps == 1
assert style.update(0.5, False) is True # at interval -> beep
assert sound.beeps == 2
assert style.update(0.6, True) is False # press -> stop
print("simple self-check ok")