Files
pdtv26/box/body/brain.py
T
dckc 190600a696 feat(box): the box's NixOS system as a module, and lib.mkBox from a few names
The box within reach of the couch: a Raspberry Pi 3B with the AIY Voice
HAT, from the first household's configuration, made generic.

- box/body: the button service, in Python: press and talk, turns by
  voice, a press interrupts; the look signal
- box/*.js: the ir and look capabilities, behind gates, for the brain;
  the ask client, the box's side of a conversation
- box/module.nix: the services, each confined to the devices and
  addresses it needs; the private network as an option (a tailnet by
  default); the Pico found by its USB IDs, as /dev/pdtv26-ir
- box/voicehat.nix: the Voice HAT's device tree overlay and ALSA setup
- lib.mkBox: a box's whole system from its name, the home server's,
  the Wi-Fi network's, and who looks after it
- checks: box-js, box-py (doctests and pyflakes), and box-system (an
  example box's system evaluates)

Generated-by: Claude Opus 5.5
2026-12-02 18:57:03 -06:00

76 lines
2.3 KiB
Python

"""What the box hears, and the brain: each a client bound to its one server.
The clients take their keys from systemd's credentials, not argv.
"""
import json
import logging
from button import PRESSED
ANSWER_S = 150 # the channel gives up at 120 s
class Hear:
"""transcribe(wav): the speech capability (hear-client, bound to its URL)."""
def __init__(self, hear_client):
self.__client = hear_client
async def transcribe(self, wav):
return (await self.__client.run(stdin=wav)).decode()
def answer(line):
"""One line from ask-client, as converse takes it.
>>> answer(b'{"say": "Let me try."}')
('say', 'Let me try.')
>>> answer(b'{"reply": "Bye!", "end": true}')
('reply', 'Bye!', True)
"""
event = json.loads(line)
if "say" in event:
return ("say", event["say"])
return ("reply", event["reply"], bool(event.get("end")))
class Brain:
"""ask(text, convo) yields ("say", text)s, 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.
"""
def __init__(self, ask_client, button):
self.__client, self.__button = ask_client, button
async def ask(self, text, convo):
proc = await self.__client.spawn(convo)
proc.stdin.write(text.encode())
await proc.stdin.drain()
proc.stdin.close()
try:
while True:
line = await self.__button.race(proc.stdout.readline(), timeout=ANSWER_S)
if line is PRESSED:
yield ("press",)
return
if not line:
await proc.wait()
err = (await proc.stderr.read()).decode().strip()
raise IOError(f"ask-client exit {proc.returncode}: {err}")
event = answer(line)
yield event
if event[0] == "reply":
return
finally:
if proc.returncode is None:
proc.kill()
await proc.wait()
async def end(self, convo):
try:
await self.__client.run(convo, "end", timeout=15)
except Exception as err:
logging.info(f"{convo}: telling the brain it ended failed: {err}")