"""The box's speaker volume: the softvol named speaker (../voicehat.nix), which the brain may nudge. The brain asks for louder or softer, in percentage points, with a reply; the box keeps the level within its own bounds, so no reply can make it silent or painfully loud. """ import re LOWEST, HIGHEST = 10, 80 # percent; full volume is too loud for a living room def percent(amixer_out): """The level amixer sget reports, in percent. >>> percent(b"Simple mixer control 'speaker',0\\n Front Left: 115 [45%]\\n Front Right: 115 [45%]\\n") 45 """ found = re.search(rb"\[(\d+)%\]", amixer_out) if not found: raise IOError(f"no level in amixer's output: {amixer_out[:200]!r}") return int(found.group(1)) def nudge(level, louder, lowest=LOWEST, highest=HIGHEST): """level, louder by so many points, within bounds. >>> nudge(45, 10), nudge(45, -10), nudge(75, 30), nudge(15, -30) (55, 35, 80, 10) """ return max(lowest, min(highest, level + louder)) class Mixer: """louder(points) changes the speaker's level and returns the new one, in percent. amixer is a Command for amixer on the box's sound card (amixer -c voicehat). >>> import asyncio >>> class Amixer: ... level = 45 ... async def run(self, *args): ... print(args) ... if args[-1].endswith("%"): self.level = int(args[-1][:-1]) ... return f" Front Left: 0 [{self.level}%]".encode() >>> asyncio.run(Mixer(Amixer()).louder(50)) ('sget', 'speaker') ('-q', 'sset', 'speaker', '80%') 80 """ def __init__(self, amixer): self.__amixer = amixer async def louder(self, points): level = nudge(percent(await self.__amixer.run("sget", "speaker")), int(points)) await self.__amixer.run("-q", "sset", "speaker", f"{level}%") return level