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
+14 -52
View File
@@ -1,5 +1,3 @@
import array
import math
import os
import sys
import time
@@ -73,10 +71,10 @@ DEFAULT_MUSIC_FILE = "Laid Back - Sunshine Reggae.mp3"
def setup():
"""Initialize GPIO and audio hardware. Call once before running.
"""Initialize GPIO and the audio engine. Call once before running.
Audio playback itself is owned by each style via the injected ``Sound``
capability, so this only brings up the mixer and pins.
Each style owns its own ringing tone via pygame directly; this only brings
up the mixer and the GPIO pins.
"""
GPIO.setmode(GPIO.BCM)
GPIO.setup(LED_PIN, GPIO.OUT)
@@ -87,48 +85,6 @@ def setup():
pygame.mixer.init()
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 from ``pre_init`` (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 Sound:
"""Audio capability injected into styles so each can own its ringing tone."""
def __init__(self):
self._beep = pygame.mixer.Sound(_BEEP_BUFFER)
def play_music(self, path: str):
"""Load and play a music file on an endless loop."""
try:
pygame.mixer.music.load(path)
pygame.mixer.music.set_volume(1.0)
pygame.mixer.music.play(-1)
except Exception as e:
logging.error(f"Error loading audio file: {e}")
if "pytest" not in sys.modules:
sys.exit(1)
def play_beep(self):
"""Play one short beep tone."""
self._beep.play()
def set_led(on):
"""Turns the LED on or off (LOW = ON, HIGH = OFF)"""
if "GPIO" in globals() and hasattr(GPIO, "output"):
@@ -145,18 +101,24 @@ def run_alarm(
):
"""Run the alarm clock with the given style until the style signals stop.
The runner owns only the shared button sampling and cleanup; each style
owns its own ringing tone (via the injected ``Sound``) and LED behaviour.
The runner owns only the audio engine lifecycle (mixer init/quit), button
sampling, and cleanup; each style owns its own ringing tone (via pygame
directly) and LED behaviour.
"""
style_cls = get_style(style_name) # validate before touching hardware
if music_file is None:
music_file = os.environ.get("MUSIC_FILE", DEFAULT_MUSIC_FILE)
setup()
sound = Sound()
style = style_cls(set_led, sound, music_file)
style = style_cls(set_led, music_file)
logging.info("Alarm clock started.")
style.start() # style kicks off its own tone + initial LED
try:
style.start() # style kicks off its own tone + initial LED
except Exception:
logging.exception("Error starting alarm")
if "pytest" not in sys.modules:
sys.exit(1)
raise
try:
while True: