Screen switch: a blubb on every switch, and Del on the kiosk keyboard

ScreenService plays a synthesised two-bubble "blubb" (musicmouse.blubb) after each
switch, through aplay on the music's ALSA device at the player's volume: rising for
on, falling for off, going by the last word the toggle command prints. Nothing plays
with simulated audio or at volume 0. Built from samples rather than shipped as a
file, like the front-end's WebAudio blips, so its loudness follows the volume.

Del maps to a new "screen" action on every page, which App.tsx sends to the new
POST /api/screen/toggle only when the page is served from localhost - the kiosk on
the device - so Del on a tablet does not switch off a screen in another room.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-10-03 17:00:37 +02:00
parent 2d0caeb732
commit 92305bece0
11 changed files with 262 additions and 19 deletions

View File

@@ -3,13 +3,17 @@
from __future__ import annotations
import asyncio
import io
import os
import shlex
import sys
import wave
from collections.abc import AsyncIterator
from pathlib import Path
import pytest
from musicmouse.blubb import RATE, blubb_wav
from musicmouse.bus import EventBus
from musicmouse.config import ScreenConfig
from musicmouse.events import ToggleScreenRequested
@@ -36,8 +40,14 @@ async def _settle(service: ScreenService) -> None:
await asyncio.sleep(0.01)
async def _started(bus: EventBus, config: ScreenConfig) -> tuple[ScreenService, asyncio.Task[None]]:
service = ScreenService(bus, config)
async def _started(
bus: EventBus,
config: ScreenConfig,
*,
alsa_device: str | None = None,
volume: float = 0.5,
) -> tuple[ScreenService, asyncio.Task[None]]:
service = ScreenService(bus, config, alsa_device=alsa_device, volume=lambda: volume)
task = asyncio.create_task(service.run())
await asyncio.sleep(0) # let it subscribe
return service, task
@@ -108,3 +118,69 @@ async def test_a_hung_command_is_killed(bus: EventBus, caplog: pytest.LogCapture
task.cancel()
assert "killed" in caplog.text
# ------------------------------------------------------------------------ the blubb
def test_the_blubb_is_a_short_mono_wav() -> None:
with wave.open(io.BytesIO(blubb_wav(on=True, gain=0.5))) as wav:
assert (wav.getnchannels(), wav.getsampwidth(), wav.getframerate()) == (1, 2, RATE)
assert 0.1 < wav.getnframes() / RATE < 0.5
def test_on_and_off_sound_different() -> None:
assert blubb_wav(on=True, gain=0.5) != blubb_wav(on=False, gain=0.5)
@pytest.fixture
def fake_aplay(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path:
"""An ``aplay`` on PATH that records its arguments and what it was fed."""
bin_dir = tmp_path / "bin"
bin_dir.mkdir()
record = tmp_path / "aplay"
script = bin_dir / "aplay"
script.write_text(
f'#!/bin/sh\necho "$@" > {shlex.quote(str(record))}.args\n'
f"cat > {shlex.quote(str(record))}.wav\n"
)
script.chmod(0o755)
monkeypatch.setenv("PATH", f"{bin_dir}:{os.environ['PATH']}")
return record
async def test_a_switch_plays_the_blubb_its_way(bus: EventBus, fake_aplay: Path) -> None:
service, task = await _started(
bus, ScreenConfig(toggle_command=_python("print('off')")), alsa_device="softvol_effects"
)
try:
await bus.emit_and_wait(ToggleScreenRequested(source="lirc"))
await _settle(service)
finally:
task.cancel()
assert Path(f"{fake_aplay}.args").read_text().split() == ["-q", "-D", "softvol_effects", "-"]
assert Path(f"{fake_aplay}.wav").read_bytes() == blubb_wav(on=False, gain=0.35 * 0.5)
@pytest.mark.parametrize(
("output", "alsa_device", "volume"),
[
("print('on')", None, 0.5), # simulated audio
("print('on')", "softvol_effects", 0.0), # muted
("print('done')", "softvol_effects", 0.5), # no direction to go by
],
)
async def test_no_blubb(
bus: EventBus, fake_aplay: Path, output: str, alsa_device: str | None, volume: float
) -> None:
service, task = await _started(
bus, ScreenConfig(toggle_command=_python(output)), alsa_device=alsa_device, volume=volume
)
try:
await bus.emit_and_wait(ToggleScreenRequested(source="lirc"))
await _settle(service)
finally:
task.cancel()
assert not Path(f"{fake_aplay}.wav").exists()

View File

@@ -18,6 +18,7 @@ import pytest
from fastapi import FastAPI
from musicmouse.config import WebConfig, load_config
from musicmouse.events import ToggleScreenRequested
from musicmouse.library.analysis import BeatGrid, TrackCurves
from musicmouse.library.models import track_key
from musicmouse.services.web.service import build_app
@@ -227,6 +228,17 @@ async def test_transport_commands_reach_the_player(client: Client, sim: Simulati
assert sim.player.is_playing
async def test_the_screen_toggle_is_an_intent(client: Client, sim: Simulation) -> None:
seen: list[ToggleScreenRequested] = []
sim.bus.subscribe(ToggleScreenRequested, seen.append)
response = await client.post("/api/screen/toggle")
await sim.bus.drain()
assert response.status_code == 204
assert [event.source for event in seen] == ["web"]
async def test_seek_moves_the_position(client: Client, sim: Simulation) -> None:
album = await album_by_title(client, "Fuchs")
await client.post("/api/play", json={"album_id": album["id"]})
@@ -245,9 +257,7 @@ async def test_seeking_backwards_is_rejected(client: Client) -> None:
# ------------------------------------------------------------------------- volume
async def test_full_volume_means_the_configured_ceiling(
client: Client, sim: Simulation
) -> None:
async def test_full_volume_means_the_configured_ceiling(client: Client, sim: Simulation) -> None:
"""The child sees 0..100; the config's max of 60 never crosses the API boundary."""
response = await client.post("/api/volume", json={"percent": 100})
assert response.status_code == 204
@@ -257,18 +267,14 @@ async def test_full_volume_means_the_configured_ceiling(
assert (await client.get("/api/state")).json()["volume"] == 100
async def test_volume_scales_across_the_allowed_range(
client: Client, sim: Simulation
) -> None:
async def test_volume_scales_across_the_allowed_range(client: Client, sim: Simulation) -> None:
await client.post("/api/volume", json={"percent": 50})
await sim.bus.drain()
assert sim.player.volume == 30
assert (await client.get("/api/state")).json()["volume"] == 50
async def test_volume_steps_are_relative_to_the_percentage(
client: Client, sim: Simulation
) -> None:
async def test_volume_steps_are_relative_to_the_percentage(client: Client, sim: Simulation) -> None:
await client.post("/api/volume", json={"percent": 50})
await sim.bus.drain()
await client.post("/api/volume", json={"delta_percent": 10})
@@ -325,9 +331,10 @@ async def test_a_new_client_is_sent_a_snapshot_before_any_deltas(api: FastAPI) -
async def test_a_state_change_reaches_every_client(api: FastAPI, sim: Simulation) -> None:
async with websocket_connect(api, "/api/ws") as first, websocket_connect(
api, "/api/ws"
) as second:
async with (
websocket_connect(api, "/api/ws") as first,
websocket_connect(api, "/api/ws") as second,
):
await first.next_json()
await second.next_json()