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
This commit is contained in:
dckc committed 2026-12-02 18:57:03 -06:00
1 parent 2e7156dc36
commit 190600a696
35 files changed
+2152 -3

No files matched your search

+119
View File
@@ -0,0 +1,119 @@
"""The box's button service: press to start a conversation; take turns by talking; press to interrupt.
A press opens a conversation: the box chimes (open), the LED lights, and the mics listen until
the speaker has been quiet a while. The box chimes again (gotit) and the LED blinks while the
agent thinks: the speech capability transcribes the turn, and the brain answers it through the
ask capability, perhaps saying a few words first. The box speaks, chimes (turn), and listens
again. The conversation ends when the brain says goodbye, when no one speaks for a while, or
when someone presses the button while the box listens; the box chimes bye. A press while the
agent thinks or speaks interrupts it: it stops, and it's their turn.
While the brain looks through the camera (../look.js), the box taps and flashes (look_signal.py).
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.
"""
import asyncio
import logging
from functools import partial
from brain import Brain, Hear
from button import Button
from command import Command
from converse import converse
from gpio import HatLines
from hearing import ARECORD_ARGS, Mics
from light import Light
from look_signal import LookSignal
from status import Status, ignore, poster
from voice import Speaker, Voice
def activated_socket(environ, getpid, socket):
"""The socket systemd passed, as fd 3 (socket activation), or None.
>>> activated_socket({"LISTEN_FDS": "1", "LISTEN_PID": "42"}, lambda: 42, lambda fileno: f"fd {fileno}")
'fd 3'
>>> activated_socket({}, lambda: 42, None) is None
True
"""
if environ.get("LISTEN_FDS") == "1" and environ.get("LISTEN_PID") == str(getpid()):
return socket(fileno=3)
return None
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]
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,
earcons, state_dir, *status_url) = argv[1:]
command = partial(Command, create_subprocess_exec)
loop = asyncio.get_running_loop()
lines = HatLines(request_lines, "/dev/gpiochip0")
button = Button()
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)
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)
brain = Brain(command(ask_client, ask_url), button)
background = [asyncio.create_task(light.run())]
note = ignore
if status_url:
status = Status(poster(open_connection, status_url[0]), sleep)
background += [asyncio.create_task(job) for job in (status.run(), status.heartbeat())]
note = status.note
listener = activated_socket(environ, getpid, socket)
if listener:
await start_unix_server(LookSignal(light, speaker.play, note).handle, sock=listener)
else:
logging.info("no look socket from systemd: the brain can't look")
logging.info("ready: press to start a conversation")
note("ready")
while True:
await button.wait()
convo = now().strftime("%Y%m%d-%H%M%S")
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,
logging.info, note)
button.pressed() # presses during goodbye don't start another
for task in background:
if task.done():
raise RuntimeError(f"a background job stopped: {task.exception()!r}")
if __name__ == "__main__":
def _script_io():
import os
import socket
import sys
import time
from datetime import datetime
from pathlib import Path
import gpiod
logging.basicConfig(level=logging.INFO, format="%(message)s", stream=sys.stdout)
return asyncio.run(main(
argv=list(sys.argv), environ=dict(os.environ), getpid=os.getpid, cwd=Path.cwd(),
request_lines=gpiod.request_lines, socket=socket.socket,
create_subprocess_exec=asyncio.create_subprocess_exec,
open_connection=asyncio.open_connection, start_unix_server=asyncio.start_unix_server,
sleep=asyncio.sleep, monotonic=time.monotonic, now=datetime.now,
))
raise SystemExit(_script_io())
+75
View File
@@ -0,0 +1,75 @@
"""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}")
+81
View File
@@ -0,0 +1,81 @@
"""The box's button: presses, queued as they come, whatever the box is doing."""
import asyncio
PRESSED = "pressed" # what race() returns when the button wins
class Presses:
"""Turn (falling?, t_ns) edges into ("down", t_ns) and ("up", held_s) events.
Repeated edges in one direction (bounce that outlasts the debounce) are ignored,
as is a release before any press.
>>> p = Presses()
>>> [p.edge(*e) for e in [(False, 0), (True, 10), (True, 11), (False, 2_510_000_000)]]
[None, ('down', 10), None, ('up', 2.51)]
"""
def __init__(self):
self.down_at = None
def edge(self, falling, t_ns):
if falling and self.down_at is None:
self.down_at = t_ns
return ("down", t_ns)
if not falling and self.down_at is not None:
held = round((t_ns - self.down_at) / 1e9, 2)
self.down_at = None
return ("up", held)
return None
class Button:
"""feed(edges) queues presses; wait() awaits one; pressed() doesn't wait;
race(aw) awaits aw unless the button is pressed first.
>>> async def demo():
... b = Button()
... b.feed([(True, 1), (False, 2)])
... first = await b.race(asyncio.sleep(9, "slept"))
... second = await b.race(asyncio.sleep(0, "slept"))
... return first, second, b.pressed()
>>> asyncio.run(demo())
('pressed', 'slept', False)
"""
def __init__(self):
self.__presses = Presses()
self.__q = asyncio.Queue()
def feed(self, edges):
for edge in edges:
if (self.__presses.edge(*edge) or ("",))[0] == "down":
self.__q.put_nowait(True)
async def wait(self):
await self.__q.get()
def pressed(self):
"""Whether there were any presses since last asked; forgets them."""
hit = False
while not self.__q.empty():
self.__q.get_nowait()
hit = True
return hit
async def race(self, aw, timeout=None):
"""aw's result; or PRESSED if the button is pressed first; TimeoutError after timeout s."""
work = asyncio.ensure_future(aw)
if self.pressed():
work.cancel()
return PRESSED
press = asyncio.ensure_future(self.__q.get())
done, pending = await asyncio.wait({work, press}, timeout=timeout,
return_when=asyncio.FIRST_COMPLETED)
for p in pending:
p.cancel()
if press in done:
return PRESSED
if work in done:
return work.result()
raise TimeoutError(f"nothing in {timeout} s")
+46
View File
@@ -0,0 +1,46 @@
"""Command: the authority to run one program, with its leading arguments fixed.
Each part of the box gets the commands it needs and no others: the mics get arecord, not aplay;
the brain gets ask-client bound to the brain's URL, and can't point it elsewhere.
"""
import asyncio
from asyncio.subprocess import PIPE # a constant: no authority
class Command:
"""One program, and the arguments every use of it starts with.
exec_ is asyncio.create_subprocess_exec, or a fake:
>>> class Proc:
... returncode = 0
... async def communicate(self, stdin): return (b"heard: " + stdin, b"")
>>> async def fake_exec(*argv, **pipes):
... print(argv)
... return Proc()
>>> hear = Command(fake_exec, "/bin/hear-client", "ws://home:8024/")
>>> asyncio.run(hear.run(stdin=b"clip"))
('/bin/hear-client', 'ws://home:8024/')
b'heard: clip'
"""
def __init__(self, exec_, *fixed):
self.__exec, self.__fixed = exec_, fixed
self.name = fixed[0].rsplit("/", 1)[-1]
async def spawn(self, *args, stdin=True, stdout=True, stderr=True):
"""Start it; True means a pipe to that stream. Returns the process."""
return await self.__exec(*self.__fixed, *args, stdin=PIPE if stdin else None,
stdout=PIPE if stdout else None, stderr=PIPE if stderr else None)
async def start(self, *args):
"""Start it and let it run: no pipes, not waited for."""
return await self.spawn(*args, stdin=False, stdout=False, stderr=False)
async def run(self, *args, stdin=b"", timeout=60):
"""Run it with stdin; return its stdout, or raise IOError with its stderr."""
proc = await self.spawn(*args)
out, err = await asyncio.wait_for(proc.communicate(stdin), timeout)
if proc.returncode:
raise IOError(f"{self.name} exit {proc.returncode}: {err.decode().strip()}")
return out
+171
View File
@@ -0,0 +1,171 @@
"""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.
"""
from contextlib import aclosing
async def converse(convo, listen, transcribe, ask, speak, play, 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",).
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.
>>> import asyncio
>>> def script(*turns):
... it = iter(turns)
... async def listen(skip): return next(it)
... return listen
>>> async def ask(text, convo):
... if text == "Switch to the PC.":
... yield ("say", "Let me try.")
... yield ("reply", "Done.", False)
... elif text == "Thanks!":
... yield ("reply", "You're welcome. Bye!", True)
... else:
... yield ("press",)
>>> async def transcribe(clip): return clip
>>> 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,
... 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)
play open
led True
led False
play gotit
thinking True
k1 heard: Switch to the PC.
thinking False
speak Let me try.
thinking True
thinking False
speak Done.
thinking False
play turn
led True
led False
play gotit
thinking True
k1 heard: Thanks!
thinking False
speak You're welcome. Bye!
thinking False
k1: the brain said goodbye
play bye
end k1
A press while the agent thinks interrupts it; silence ends the conversation:
>>> run("k2", script(("speech", "Tell me a long story."), ("quiet", None)), **ops)
play open
led True
led False
play gotit
thinking True
k2 heard: Tell me a long story.
thinking False
thinking False
k2: interrupted
play turn
led True
led False
k2: quiet; goodbye
play bye
end k2
Nothing heard, or a failure, gets the huh earcon and another turn; a press while
the box listens says goodbye:
>>> async def deaf_to_hello(clip):
... if clip == "hello": raise IOError("speech server unreachable")
... return clip
>>> run("k3", script(("speech", "[BLANK_AUDIO]"), ("speech", "hello"), ("press", None)),
... **dict(ops, transcribe=deaf_to_hello))
play open
led True
led False
play gotit
thinking True
thinking False
play huh
led True
led False
play gotit
thinking True
k3: transcribe failed: speech server unreachable
thinking False
play huh
led True
led False
k3: press; goodbye
play bye
end k3
"""
skip = await play("open")
while True:
led(True)
kind, clip = None, None
try:
kind, clip = await listen(skip)
except Exception as err:
kind = None
log(f"{convo}: listen failed: {err}")
finally:
led(False)
if kind != "speech":
if kind:
log(f"{convo}: {kind}; goodbye")
reason = kind or "listen failed"
break
await play("gotit")
thinking(True)
try:
text = (await transcribe(clip)).strip()
except Exception as err:
log(f"{convo}: transcribe failed: {err}")
text = ""
if not text or text.startswith("["): # [BLANK_AUDIO] and the like
thinking(False)
note("huh")
skip = await play("huh")
continue
log(f"{convo} heard: {text}")
note("turn")
ended = interrupted = failed = False
try:
async with aclosing(ask(text, convo)) as events: # a break closes it now, not someday
async for event in events:
thinking(False)
if event[0] == "press" or not await speak(event[1]):
interrupted = True
break
if event[0] == "reply":
ended = event[2]
break
thinking(True)
except Exception as err:
log(f"{convo}: ask failed: {err}")
failed = True
finally:
thinking(False)
if ended:
log(f"{convo}: the brain said goodbye")
reason = "goodbye"
break
if interrupted:
log(f"{convo}: interrupted")
note("interrupt")
if failed:
note("huh")
skip = await play("huh" if failed else "turn")
await play("bye")
note("end", reason=reason)
await end(convo)
+58
View File
@@ -0,0 +1,58 @@
"""The box's GPIO, narrowed: the Voice HAT's button and LED, and nothing else on the chip.
The Voice HAT wires the button to GPIO 23 (pressed pulls it low) and its LED to GPIO 25.
"""
from datetime import timedelta
from gpiod import EdgeEvent, LineSettings # data types: no authority
from gpiod.line import Bias, Direction, Edge, Value
BUTTON, LED = 23, 25
CONFIG = {
BUTTON: LineSettings(direction=Direction.INPUT, bias=Bias.PULL_UP, edge_detection=Edge.BOTH,
debounce_period=timedelta(milliseconds=20)),
LED: LineSettings(direction=Direction.OUTPUT, output_value=Value.INACTIVE),
}
def edge_of(event):
"""An edge event as (falling?, t_ns).
>>> class Ev: event_type, timestamp_ns = EdgeEvent.Type.FALLING_EDGE, 10
>>> edge_of(Ev())
(True, 10)
"""
return (event.event_type == EdgeEvent.Type.FALLING_EDGE, event.timestamp_ns)
class HatLines:
"""The button and LED lines, claimed from chip with request_lines (gpiod.request_lines).
fileno() is readable when the button has new edges; read_edges() returns them, as
(falling?, t_ns). set_led(on) lights the LED or not.
>>> class Request:
... fd = 7
... def set_value(self, line, value): print(line, value)
>>> def request_lines(chip, consumer, config):
... print(chip, consumer, sorted(config))
... return Request()
>>> lines = HatLines(request_lines, "/dev/gpiochip0")
/dev/gpiochip0 pdtv26-box [23, 25]
>>> lines.fileno()
7
>>> lines.set_led(True)
25 Value.ACTIVE
"""
def __init__(self, request_lines, chip):
self.__request = request_lines(chip, consumer="pdtv26-box", config=CONFIG)
def fileno(self):
return self.__request.fd
def read_edges(self):
return [edge_of(ev) for ev in self.__request.read_edge_events()]
def set_led(self, on):
self.__request.set_value(LED, Value.ACTIVE if on else Value.INACTIVE)
+155
View File
@@ -0,0 +1,155 @@
"""The box's ears: the mics, and when a turn is over.
The mics run in their own format, S32_LE stereo at 16 kHz: the Voice HAT's amp and mics share
one I2S bus, so the box's earcons play at that rate while the mics listen.
"""
import array
import asyncio
import io
import logging
import math
import wave
RATE, CHANNELS, SAMPLE_BYTES = 16000, 2, 4 # the mics' own format: S32_LE stereo
FRAME_S = 0.03
FRAME_BYTES = int(RATE * FRAME_S) * CHANNELS * SAMPLE_BYTES
LEAD_S, TAIL_S = 0.4, 0.3 # kept around the speech, so whisper hears its first word whole
ARECORD_ARGS = ("-q", "-D", "hw:CARD=voicehat,DEV=0", "-f", "S32_LE", "-c", str(CHANNELS),
"-r", str(RATE), "-t", "raw")
def level_db(frame):
"""Loudness of one frame of S32_LE stereo, in dBFS, from its first channel, DC removed.
>>> level_db(array.array('i', [2**30, 0, -2**30, 0] * 240).tobytes())
-6.0
>>> level_db(bytes(16))
-120.0
"""
x = array.array('i', frame)[0::CHANNELS]
mean = sum(x) / len(x)
rms = math.sqrt(sum((v - mean) ** 2 for v in x) / len(x))
return round(max(20 * math.log10(rms / 2**31) if rms else -120.0, -120.0), 1)
class Endpointer:
"""Decide from frame levels when a turn is over.
Speech is a frame margin_db above the noise floor; a turn starts after start_frames of
speech and ends after end_s without. The floor follows quiet frames down at once, and up
slowly. Frames during skip_s (the box's own earcon) are ignored.
feed(level) returns None, "done" (spoken, then quiet), "quiet" (nothing said in quiet_s),
or "long" (max_s). start and end are frame indexes of the speech.
>>> ep = Endpointer(skip_s=0.09, end_s=0.09, quiet_s=0.3)
>>> [ep.feed(db) for db in [-40, -40, -40, -78, -77, -50, -48, -50, -78, -78, -78]]
[None, None, None, None, None, None, None, None, None, None, 'done']
>>> ep.start, ep.end
(5, 7)
>>> ep = Endpointer(quiet_s=0.15)
>>> [ep.feed(db) for db in [-78] * 5]
[None, None, None, None, 'quiet']
>>> ep = Endpointer(max_s=0.15)
>>> [ep.feed(db) for db in [-50] * 5]
[None, None, None, None, 'long']
"""
def __init__(self, skip_s=0.0, margin_db=15, floor_db=-70, start_frames=3,
end_s=1.5, quiet_s=8.0, max_s=30.0, frame_s=FRAME_S):
self.skip = round(skip_s / frame_s)
self.margin, self.floor = margin_db, floor_db
self.start_frames = start_frames
self.end_frames = round(end_s / frame_s)
self.quiet_frames = round(quiet_s / frame_s)
self.max_frames = round(max_s / frame_s)
self.n, self.run = 0, 0
self.start = self.end = None
self.last_speech = None
def feed(self, level):
i = self.n
self.n += 1
if i < self.skip:
return None
speech = level > self.floor + self.margin
if not speech:
self.floor = level if level < self.floor else self.floor + 0.05
if self.start is None:
self.run = self.run + 1 if speech else 0
if self.run >= self.start_frames:
self.start = i - self.start_frames + 1
self.last_speech = i
elif i - self.skip + 1 >= self.quiet_frames:
return "quiet"
elif speech:
self.last_speech = i
elif self.last_speech is not None and i - self.last_speech >= self.end_frames:
self.end = self.last_speech
return "done"
if self.n >= self.max_frames:
self.end = self.last_speech if self.last_speech is not None else i
return "long"
return None
def wav_bytes(frames):
"""Frames of the mics' raw audio, as a WAV file.
>>> data = wav_bytes([bytes(FRAME_BYTES)] * 2)
>>> data[:4], len(data) - 44 == 2 * FRAME_BYTES
(b'RIFF', True)
"""
buf = io.BytesIO()
with wave.open(buf, "wb") as w:
w.setnchannels(CHANNELS)
w.setsampwidth(SAMPLE_BYTES)
w.setframerate(RATE)
w.writeframes(b"".join(frames))
return buf.getvalue()
class Mics:
"""listen(skip_s, button) returns ("speech", wav), ("quiet", None), or ("press", None).
arecord is a Command for arecord with ARECORD_ARGS; keep(wav) keeps the latest clip.
"""
def __init__(self, arecord, keep):
self.__arecord, self.__keep = arecord, keep
async def listen(self, skip_s, button):
proc = await self.__arecord.spawn(stdin=False)
ep = Endpointer(skip_s=skip_s + 0.1) # and the mics' startup burst
frames = []
try:
while True:
try:
frame = await proc.stdout.readexactly(FRAME_BYTES)
except asyncio.IncompleteReadError:
await proc.wait()
err = (await proc.stderr.read()).decode().strip()
raise IOError(f"arecord exit {proc.returncode}: {err}")
frames.append(frame)
if button.pressed():
if ep.start is None:
return ("press", None)
ep.end = len(frames) - 1
break
outcome = ep.feed(level_db(frame))
if outcome == "quiet":
return ("quiet", None)
if outcome:
break
finally:
if proc.returncode is None:
proc.terminate()
await proc.wait()
if ep.start is None or ep.end is None:
return ("quiet", None)
lead, tail = round(LEAD_S / FRAME_S), round(TAIL_S / FRAME_S)
wav = wav_bytes(frames[max(ep.start - lead, 0):ep.end + tail + 1])
try:
self.__keep(wav)
except OSError as err:
logging.info(f"keeping the clip failed: {err}")
return ("speech", wav)
+83
View File
@@ -0,0 +1,83 @@
"""The box's LED: on while the mics are open, blinking while the agent thinks, double-flashing while it looks.
run() draws it from the state, so looking can show over thinking, and give way.
"""
from contextlib import contextmanager
BLINK_S = 0.25 # thinking: on and off, twice a second
LOOK_FLASHES = ((0.0, 0.1), (0.2, 0.3)) # looking: two quick flashes...
LOOK_PERIOD_S = 0.8 # ...each 0.8 s
def led_at(mics, thinking, looking, t):
"""Whether the LED is lit at time t (seconds): looking outranks thinking, which outranks the mics.
Looking double-flashes:
>>> [led_at(False, False, True, t / 10) for t in range(8)]
[True, False, True, False, False, False, False, False]
Thinking blinks twice a second; otherwise the LED shows whether the mics are open:
>>> [led_at(True, True, False, t / 4) for t in range(4)]
[True, False, True, False]
>>> led_at(True, False, False, 7.3), led_at(False, False, False, 7.3)
(True, False)
"""
if looking:
phase = t % LOOK_PERIOD_S
return any(start <= phase < stop for start, stop in LOOK_FLASHES)
if thinking:
return int(t / BLINK_S) % 2 == 0
return mics
class Light:
"""The LED's state; run() draws it, on the event loop.
>>> light = Light(set_led=print, monotonic=lambda: 0.0, sleep=None)
>>> light.lit()
False
>>> light.mics(True)
>>> light.lit()
True
>>> with light.looking():
... light.looking_now()
True
>>> light.looking_now()
False
"""
def __init__(self, set_led, monotonic, sleep):
self.__set, self.__monotonic, self.__sleep = set_led, monotonic, sleep
self.__mics = self.__thinking = False
self.__looks = 0
def mics(self, on):
self.__mics = on
def thinking(self, on):
self.__thinking = on
@contextmanager
def looking(self):
self.__looks += 1
try:
yield
finally:
self.__looks -= 1
def looking_now(self):
return self.__looks > 0
def lit(self):
return led_at(self.__mics, self.__thinking, self.looking_now(), self.__monotonic())
async def run(self):
shown = None
while True:
want = self.lit()
if want != shown:
self.__set(want)
shown = want
await self.__sleep(0.02)
+49
View File
@@ -0,0 +1,49 @@
"""Showing that the box is looking: a tap (the look earcon) and a double-flash, while look-server looks.
look-server connects to the socket systemd gives the button service (pdtv26-button.socket) and waits for
"looking" before it grabs a frame: no indication, no look. The flashing lasts as long as the
connection.
"""
import asyncio
import logging
LONGEST_LOOK_S = 60 # a look takes seconds; don't flash forever for a stuck one
class LookSignal:
"""handle(reader, writer) serves one look; for asyncio.start_unix_server.
>>> class Light:
... def looking(self):
... import contextlib
... return contextlib.nullcontext(print("flashing"))
>>> async def play(name): print("play", name)
>>> class Reader:
... async def read(self): return b""
>>> class Writer:
... def write(self, data): print("sent", data)
... async def drain(self): pass
... def close(self): pass
>>> asyncio.run(LookSignal(Light(), play, lambda kind: print("note", kind)).handle(Reader(), Writer()))
flashing
play look
sent b'looking\\n'
note look
"""
def __init__(self, light, play, note):
self.__light, self.__play, self.__note = light, play, note
async def handle(self, reader, writer):
with self.__light.looking():
try:
await self.__play("look")
writer.write(b"looking\n")
await writer.drain()
await asyncio.wait_for(reader.read(), LONGEST_LOOK_S) # until look-server hangs up
except (OSError, asyncio.TimeoutError) as err:
logging.info(f"look: {err!r}")
finally:
writer.close()
logging.info("looked")
self.__note("look")
+91
View File
@@ -0,0 +1,91 @@
"""The box's reports to a status page: ready, each conversation, each look, and a heartbeat.
Reports wait in a queue, so a slow status server never holds the box up. A failure is logged when it
starts, and again when reports get through.
"""
import asyncio
import json
import logging
from urllib.parse import urlsplit
HEARTBEAT_S = 60
def poster(open_connection, url):
"""post(path, body): POST body, as JSON, to path on url's server, and no other.
open_connection is asyncio.open_connection, or a fake:
>>> class Writer:
... def write(self, data): pass
... async def drain(self): pass
... def close(self): pass
... async def wait_closed(self): pass
>>> def server(status):
... class Reader:
... async def readline(self): return status
... async def connect(host, port): return Reader(), Writer()
... return connect
Any 2xx is success; the rest raise:
>>> asyncio.run(poster(server(b"HTTP/1.1 204 No Content\\r\\n"), "http://home:8027")("/heartbeat", {}))
>>> post = poster(server(b"HTTP/1.1 400 Bad Request\\r\\n"), "http://home:8027")
>>> asyncio.run(post("/event", {"kind": "look"}))
Traceback (most recent call last):
...
OSError: /event: HTTP/1.1 400 Bad Request
"""
parts = urlsplit(url)
host, port, base = parts.hostname, parts.port or 80, parts.path.rstrip("/")
async def post(path, body):
data = json.dumps(body).encode()
reader, writer = await asyncio.wait_for(open_connection(host, port), 10)
try:
writer.write(f"POST {base}{path} HTTP/1.1\r\nHost: {host}\r\n"
f"Content-Type: application/json\r\nContent-Length: {len(data)}\r\n"
"Connection: close\r\n\r\n".encode() + data)
await writer.drain()
status = (await asyncio.wait_for(reader.readline(), 10)).decode().strip()
finally:
writer.close()
await writer.wait_closed()
code = status.split(" ")[1:2]
if not (code and code[0].startswith("2")):
raise OSError(f"{path}: {status}")
return post
def ignore(kind, **data):
"""note(kind, ...) for a box with no status page: it goes nowhere."""
class Status:
"""note(kind, ...) queues an event; run() sends what's queued; heartbeat() queues one a minute."""
def __init__(self, post, sleep):
self.__post, self.__sleep = post, sleep
self.__q = asyncio.Queue()
def note(self, kind, **data):
self.__q.put_nowait(("/event", {"kind": kind, "source": "pdtv26-button", **data}))
async def heartbeat(self):
while True:
self.__q.put_nowait(("/heartbeat", {}))
await self.__sleep(HEARTBEAT_S)
async def run(self):
failing = False
while True:
path, body = await self.__q.get()
try:
await self.__post(path, body)
if failing:
logging.info("status: reports get through again")
failing = False
except (OSError, asyncio.TimeoutError) as err:
if not failing:
logging.info(f"status: report failed: {err}")
failing = True
+60
View File
@@ -0,0 +1,60 @@
"""The box's voice: earcons, and speech, which a press of the button stops."""
import logging
import wave
from button import PRESSED
EARCONS = ("open", "turn", "gotit", "huh", "bye", "look")
class Speaker:
"""play(name) starts an earcon and returns its length; play_wav(wav, button) plays speech.
aplay is a Command for aplay on the speaker; sounds is the directory of earcons (a Path).
An earcon isn't waited for: it plays while the mics listen.
"""
def __init__(self, aplay, sounds):
self.__aplay, self.__sounds = aplay, sounds
self.__lengths = {}
for name in EARCONS:
with (sounds / f"{name}.wav").open("rb") as f, wave.open(f) as w:
self.__lengths[name] = w.getnframes() / w.getframerate()
async def play(self, name):
await self.__aplay.start(str(self.__sounds / f"{name}.wav"))
return self.__lengths[name]
async def play_wav(self, wav, button):
"""Play it to the end, and return True; or stop at a press, and return False."""
proc = await self.__aplay.spawn(stdout=False, stderr=False)
async def feed():
try:
proc.stdin.write(wav)
await proc.stdin.drain()
proc.stdin.close()
except (BrokenPipeError, ConnectionResetError):
pass
await proc.wait()
if await button.race(feed()) is PRESSED:
proc.terminate()
await proc.wait()
return False
return True
class Voice:
"""speak(text): the speech capability's (piper), or espeak-ng if that fails; a press stops it."""
def __init__(self, say, espeak, speaker, button):
self.__say, self.__espeak, self.__speaker, self.__button = say, espeak, speaker, button
async def speak(self, text):
try:
wav = await self.__say.run(stdin=text.encode())
except Exception as err:
logging.info(f"say failed, so espeak: {err}")
wav = await self.__espeak.run(text)
logging.info(f"saying: {text}")
return await self.__speaker.play_wav(wav, self.__button)