feat: the brain can change the box's speaker volume

"Speak up" and "too loud" now work: the reply tool takes louder, in
percentage points, and the button service nudges the speaker's softvol
before it speaks that reply, so the person hears the change at once.
The box keeps the level between 10% and 80% (body/mixer.py).

No new port or key: the volume changes only with a reply, in a
conversation someone is listening to.

Generated-by: Claude Opus 5.5
This commit is contained in:
dckc committed 2026-12-03 16:44:54 -06:00
1 parent cf503ac247
commit 5191ee9931
11 files changed
+146 -21

No files matched your search

+3 -1
View File
@@ -3,6 +3,7 @@
* @file ask-client: the box's side of a conversation with the brain, through its ask capability.
* usage: ask-client.js URL CONVERSATION < question.txt
* prints JSON lines: {"say": "..."} for each thing the brain says meanwhile,
* then, if the brain changed the volume, {"louder": N} (percentage points; negative is softer),
* then {"reply": "...", "end": false}; end is true when the brain ends the conversation.
* usage: ask-client.js URL CONVERSATION end
* tells the brain the conversation is over.
@@ -45,7 +46,8 @@ const main = async ({
}
const question = (await text(stdin)).trim();
// Cap'n Web passes the function by reference: the brain calls it back over this session.
const { text: reply, end } = await asker.ask(question, conversation, (/** @type {string} */ said) => { line({ say: said }); });
const { text: reply, end, louder } = await asker.ask(question, conversation, (/** @type {string} */ said) => { line({ say: said }); });
if (louder) line({ louder });
line({ reply, end });
} finally {
gate[Symbol.dispose]();
+6 -4
View File
@@ -13,7 +13,7 @@ While the brain looks through the camera (../look.js), the box taps and flashes
One event loop, no threads. Only _script_io() imports authority (the DisciplinedPython
recipe); main() narrows it into the parts, each of which gets only what it needs:
button and light (gpio.py, button.py, light.py), mics (hearing.py), speaker and voice
(voice.py), hear and brain (brain.py), status (status.py), and the look signal.
(voice.py), the volume (mixer.py), hear and brain (brain.py), status (status.py), and the look signal.
"""
import asyncio
import logging
@@ -27,6 +27,7 @@ from gpio import HatLines
from hearing import ARECORD_ARGS, Mics
from light import Light
from look_signal import LookSignal
from mixer import Mixer
from status import Status, ignore, poster
from voice import Speaker, Voice
@@ -46,14 +47,14 @@ def activated_socket(environ, getpid, socket):
async def main(argv, environ, getpid, cwd, request_lines, socket, create_subprocess_exec, open_connection,
start_unix_server, sleep, monotonic, now):
"""box.py APLAY ARECORD ESPEAK HEAR_CLIENT SPEAK_CLIENT SPEECH_URL ASK_CLIENT ASK_URL EARCONS STATE_DIR [STATUS_URL]
"""box.py APLAY AMIXER ARECORD ESPEAK HEAR_CLIENT SPEAK_CLIENT SPEECH_URL ASK_CLIENT ASK_URL EARCONS STATE_DIR [STATUS_URL]
HEAR_CLIENT SPEECH_URL < clip prints its transcript; SPEAK_CLIENT SPEECH_URL < text prints
a WAV of it; ASK_CLIENT ASK_URL CONVERSATION < text prints the brain's answer as JSON lines.
EARCONS is a directory of WAVs (voice.EARCONS); STATE_DIR keeps the latest clip.
STATUS_URL, if any, is a status page, told of each conversation and look, with a heartbeat.
"""
(aplay, arecord, espeak, hear_client, speak_client, speech_url, ask_client, ask_url,
(aplay, amixer, arecord, espeak, hear_client, speak_client, speech_url, ask_client, ask_url,
earcons, state_dir, *status_url) = argv[1:]
command = partial(Command, create_subprocess_exec)
loop = asyncio.get_running_loop()
@@ -63,6 +64,7 @@ async def main(argv, environ, getpid, cwd, request_lines, socket, create_subproc
loop.add_reader(lines.fileno(), lambda: button.feed(lines.read_edges()))
light = Light(lines.set_led, monotonic, sleep)
speaker = Speaker(command(aplay, "-q", "-D", "speaker"), cwd / earcons)
mixer = Mixer(command(amixer, "-c", "voicehat"))
mics = Mics(command(arecord, *ARECORD_ARGS), keep=(cwd / state_dir / "clip.wav").write_bytes)
hear = Hear(command(hear_client, speech_url))
voice = Voice(command(speak_client, speech_url), command(espeak, "--stdout"), speaker, button)
@@ -88,7 +90,7 @@ async def main(argv, environ, getpid, cwd, request_lines, socket, create_subproc
logging.info(f"{convo}: a conversation starts")
note("conversation")
await converse(convo, partial(mics.listen, button=button), hear.transcribe, brain.ask,
voice.speak, speaker.play, light.mics, light.thinking, brain.end,
voice.speak, speaker.play, mixer.louder, light.mics, light.thinking, brain.end,
logging.info, note)
button.pressed() # presses during goodbye don't start another
for task in background:
+5 -1
View File
@@ -25,17 +25,21 @@ def answer(line):
>>> answer(b'{"say": "Let me try."}')
('say', 'Let me try.')
>>> answer(b'{"louder": -10}')
('louder', -10)
>>> answer(b'{"reply": "Bye!", "end": true}')
('reply', 'Bye!', True)
"""
event = json.loads(line)
if "say" in event:
return ("say", event["say"])
if "louder" in event:
return ("louder", int(event["louder"]))
return ("reply", event["reply"], bool(event.get("end")))
class Brain:
"""ask(text, convo) yields ("say", text)s, then ("reply", text, end); or ("press",).
"""ask(text, convo) yields ("say", text)s, perhaps ("louder", points), then ("reply", text, end); or ("press",).
end(convo) tells the brain the conversation is over.
ask_client is a Command for ask-client, bound to the brain's ask capability.
+35 -4
View File
@@ -1,17 +1,18 @@
"""One conversation with the box, from the press that opened it to goodbye.
Everything it touches comes in as a function: listen, transcribe, ask, speak, play, the LED.
Everything it touches comes in as a function: listen, transcribe, ask, speak, play, the volume, the LED.
"""
from contextlib import aclosing
async def converse(convo, listen, transcribe, ask, speak, play, led, thinking, end, log,
async def converse(convo, listen, transcribe, ask, speak, play, louder, led, thinking, end, log,
note=lambda kind, **data: None):
"""One conversation, from the press that opened it to goodbye.
Async: listen(skip_s) returns ("speech", clip), ("quiet", None), or ("press", None).
play(name) starts an earcon and returns its length, which listen skips.
ask(text, convo) yields ("say", text), then ("reply", text, end); or ("press",).
ask(text, convo) yields ("say", text), perhaps ("louder", points), then ("reply", text, end); or ("press",).
louder(points) changes the speaker volume, before the reply is spoken, and returns the new level.
speak(text) returns False if a press interrupted it. end(convo) tells the brain.
Not async: led(on), thinking(on), log(msg), and
note(kind, ...) counts it for a status page: turn, huh, interrupt, end.
@@ -25,6 +26,9 @@ async def converse(convo, listen, transcribe, ask, speak, play, led, thinking, e
... if text == "Switch to the PC.":
... yield ("say", "Let me try.")
... yield ("reply", "Done.", False)
... elif text == "Speak up!":
... yield ("louder", 10)
... yield ("reply", "Is this better?", False)
... elif text == "Thanks!":
... yield ("reply", "You're welcome. Bye!", True)
... else:
@@ -33,7 +37,8 @@ async def converse(convo, listen, transcribe, ask, speak, play, led, thinking, e
>>> async def speak(text): return print("speak", text) or True
>>> async def play(name): return print("play", name) or 0.4
>>> async def end(convo): print("end", convo)
>>> ops = dict(transcribe=transcribe, ask=ask, speak=speak, play=play, end=end, log=print,
>>> async def louder(points): return 45 + points
>>> ops = dict(transcribe=transcribe, ask=ask, speak=speak, play=play, louder=louder, end=end, log=print,
... led=lambda on: print("led", on), thinking=lambda on: print("thinking", on))
>>> run = lambda convo, listen, **kw: asyncio.run(converse(convo, listen, **kw))
>>> run("k1", script(("speech", "Switch to the PC."), ("speech", "Thanks!")), **ops)
@@ -62,6 +67,26 @@ async def converse(convo, listen, transcribe, ask, speak, play, led, thinking, e
play bye
end k1
The brain can turn the volume up or down; the box does so before it speaks the reply:
>>> run("k4", script(("speech", "Speak up!"), ("press", None)), **ops)
play open
led True
led False
play gotit
thinking True
k4 heard: Speak up!
k4: volume 55%
thinking False
speak Is this better?
thinking False
play turn
led True
led False
k4: press; goodbye
play bye
end k4
A press while the agent thinks interrupts it; silence ends the conversation:
>>> run("k2", script(("speech", "Tell me a long story."), ("quiet", None)), **ops)
@@ -143,6 +168,12 @@ async def converse(convo, listen, transcribe, ask, speak, play, led, thinking, e
try:
async with aclosing(ask(text, convo)) as events: # a break closes it now, not someday
async for event in events:
if event[0] == "louder":
try:
log(f"{convo}: volume {await louder(event[1])}%")
except Exception as err:
log(f"{convo}: volume change failed: {err}")
continue
thinking(False)
if event[0] == "press" or not await speak(event[1]):
interrupted = True
+56
View File
@@ -0,0 +1,56 @@
"""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
+1 -1
View File
@@ -114,7 +114,7 @@ in
# -E -s, not -I: box.py imports its siblings in body/, from the store.
ExecStart = lib.escapeShellArgs [
"${pkgs.python3.withPackages (ps: [ ps.libgpiod ])}/bin/python3" "-E" "-s" "${./body}/box.py"
"${pkgs.alsa-utils}/bin/aplay" "${pkgs.alsa-utils}/bin/arecord" "${pkgs.espeak-ng}/bin/espeak-ng"
"${pkgs.alsa-utils}/bin/aplay" "${pkgs.alsa-utils}/bin/amixer" "${pkgs.alsa-utils}/bin/arecord" "${pkgs.espeak-ng}/bin/espeak-ng"
(script "hear-client" "${speechJs}/hear-client.js") (script "speak-client" "${speechJs}/speak-client.js")
cfg.speechUrl
(script "ask-client" "${boxJs}/ask-client.js") cfg.askUrl
+2 -1
View File
@@ -61,7 +61,8 @@
}];
# The amp has no volume control of its own, so a softvol named speaker goes in front of it; everything
# plays through it. make volume VOL=30% sets the level; persistence keeps it across reboots.
# plays through it. make volume VOL=30% sets the level, and the brain can nudge it (body/mixer.py);
# persistence keeps it across reboots.
hardware.alsa = {
enable = true;
enablePersistence = true;