Compare commits

...
1 Commits
Author SHA1 Message Date
dckc 521998b666 feat(box): the box's NixOS system as a module, and lib.mkBox from a few names
check / check (push) Canceled after 0s
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 16:18:17 -06:00
35 changed files with 2165 additions and 3 deletions

No files matched your search

+2
View File
@@ -3,3 +3,5 @@ __pycache__/
ir-pico/cache/
speech/cache/
node_modules/
box/image
box/heard.wav
+4
View File
@@ -26,3 +26,7 @@ Each module's docstring says what it is. Docs are only for what isn't code, such
### Capabilities on the wire
The connections are [Cap'n Web](https://github.com/cloudflare/capnweb) over WebSockets, on a private network such as a Tailscale tailnet. A server listens with a [gate](speech/gate.js), not the capability itself: the gate hands the capability to whoever presents its key, compared in constant time, and a client can open and call in one round trip. Keys reach services through systemd's `LoadCredential` (`$CREDENTIALS_DIRECTORY`), never through argv, the environment, or the Nix store.
### Confinement
The box's services run under systemd with `ProtectSystem=strict`, `DynamicUser` where possible, `DevicePolicy=closed` and only the devices they need (the GPIO chip and ALSA for the button; the Pico's tty for `ir`), and `IPAddressAllow` limited to the private network, plus the camera's LAN for `look` alone. `look` won't take a frame unless the button service is there to show it: it connects to the button's socket, whose group is look's alone, and waits for the box to flash and tap. [box/module.nix](box/module.nix) has the details.
+26 -1
View File
@@ -21,6 +21,29 @@ Agent: Here's the game. It started ten minutes ago.
The game isn't on 4, 5, or 9. It's on a sports network in the hundreds, behind two **Power** buttons, the **Input** button, and the cable box's remote. Our elders have done their share; let the agent do this.
## How it works
The agent has two parts: the box within reach of the couch, with an IR emitter on a cord where the TV can see it, and a home server that runs speech and the brain; the diagram draws those two apart, since they can be.
```
near the couch speech server brain host
┌───────────────┐ hear ──▶ ┌──────────────┐
│ the box │ speak ──▶ │ whisper.cpp │
│ Pi 3B │ │ piper │
│ AIY Voice HAT │ ask ──────────────────────────────▶ ┌──────────────┐
│ button + LED │ │ brain, in │
│ │ ◀──── ir (learn, send) ───────────── │ bwrap, with │
│ │ ◀──── look (one frame) ───────────── │ an MCP chan. │
└───────────────┘ └──────────────┘
└─ USB cord ─▶ Pico IR ──▶ TV, cable box
```
1. A press of the box's [button](box/body/box.py) starts a conversation, and a chime says it's your turn.
2. The box records the clip and, with its [`speech` capability](#capabilities-and-confinement), has the speech server transcribe it (whisper.cpp).
3. The box sends the text to the brain with its `ask` capability.
4. To act, the brain uses its capabilities on the box: [`ir`](box/ir.js) (send a learned code through the Pico) or [`look`](box/look.js) (one still frame from a camera aimed at the TV; the box flashes its LED and taps a sound on every look, so there's no unannounced looking).
5. With the same `speech` capability, the box has the speech server voice the brain's reply (piper), and plays the WAV.
## Capabilities and confinement
An agent in the living room should be able to do what it's for, and no more. A capability is a reference that both names a service and grants the right to use it. Each part holds capabilities for exactly the services it uses. The brain can press IR buttons and take one camera frame, but it can't reach a shell on the box or anyone's files.
@@ -31,7 +54,9 @@ The parts talk over [Cap'n Web](https://github.com/cloudflare/capnweb); [CONTRIB
The agent is built from parts you can buy and solder:
- **The IR emitter:** a Raspberry Pi Pico H with an IR transceiver ([wiring](ir-pico/wiring.md)), on a USB cord, aimed at the equipment.
- **The box:** a Raspberry Pi 3B with a Google AIY Voice Kit v1 (speaker, two mics, the button), running [NixOS](box/module.nix).
- **The IR emitter:** a Raspberry Pi Pico H with an IR transceiver ([wiring](ir-pico/wiring.md)), on a USB cord from the box, aimed at the equipment.
- **The camera:** an RTSP camera on the LAN, aimed at the TV.
## License
+70
View File
@@ -0,0 +1,70 @@
# box: the part of the agent within reach of the couch: a Raspberry Pi 3B with the AIY Voice HAT.
# Tools come from the flake: nix develop --command make test
#
# A box's system comes from lib.mkBox in a flake of your own (FLAKE), as nixosConfigurations.BOX.
# Build its image, write it to a card, put the Wi-Fi secret on it, boot the Pi:
# make image FLAKE=... BOX=...
# make card DEV=/dev/sdX # look first
# make flash DEV=/dev/sdX CONFIRM=erase # then write
# make wifi-secret SSID=...
# After that, changes go over ssh: make deploy.
FLAKE = .
BOX = box
ADMIN = $(USER)
HOST = $(BOX).local
NIX = nix --option extra-platforms aarch64-linux
DEV =
SSID =
MNT = /mnt/pdtv26-card
TEXT = Hello. Press my button and talk to me.
AMP = 100
VOL = 30%
SECS = 6
.PHONY: help test image card flash wifi-secret deploy say volume record
## list targets
help:
@awk -f ../make-help.awk $(MAKEFILE_LIST)
## the unit tests and doctests, and that a box's system evaluates, in Nix's build sandbox
test:
nix build -L --no-link ..#checks.x86_64-linux.box-js ..#checks.x86_64-linux.box-py ..#checks.x86_64-linux.box-system
## BOX's SD card image (aarch64: under qemu, unless this is an aarch64 machine)
image:
$(NIX) build -L --out-link image '$(FLAKE)#nixosConfigurations.$(BOX).config.system.build.sdImage'
ls -l image/sd-image/
## show the card at DEV, and check it's removable, on USB, and under 128 GB
card:
./card-check.sh $(DEV)
## erase the card at DEV and write the image: make flash DEV=/dev/sdX CONFIRM=erase
# Not "flash: image": image links into the Nix store, where every mtime is 1970, so make would always rebuild.
flash: card
@test "$(CONFIRM)" = erase || { echo "this erases $(DEV); add CONFIRM=erase"; exit 1; }
@test -e image || { echo "no image yet: make image"; exit 1; }
./flash.sh image/sd-image/*.img $(DEV)
## put the Wi-Fi network's PSK on the card, from the passphrase in the desktop keyring: make wifi-secret SSID=...
wifi-secret:
@test -n "$(SSID)" || { echo "which network? add SSID=..."; exit 1; }
./wifi-secret.sh '$(SSID)' $(MNT)
## build BOX's system here and switch the Pi to it, over ssh: make deploy [HOST=...]
deploy:
nixos-rebuild switch --flake '$(FLAKE)#$(BOX)' --target-host $(ADMIN)@$(HOST) --sudo --option extra-platforms aarch64-linux
## speak TEXT through the box's speaker, with espeak-ng: make say [TEXT="..."] [AMP=0..200]
say:
printf '%s\n' "$(TEXT)" | ssh $(ADMIN)@$(HOST) 'espeak-ng -a $(AMP) --stdin --stdout | aplay -q -D speaker'
## set the box's speaker volume (the softvol in front of the amp): make volume [VOL=30%]
volume:
ssh $(ADMIN)@$(HOST) 'aplay -q -D speaker -f S16_LE -d 1 /dev/zero; amixer -q -c voicehat sset speaker $(VOL) && amixer -c voicehat sget speaker | tail -1'
## chime, then record SECS seconds from the box's mics to heard.wav (32-bit stereo, 16 kHz)
record:
ssh $(ADMIN)@$(HOST) 'aplay -q -D speaker /etc/pdtv26-earcons/open.wav && arecord -q -D hw:CARD=voicehat,DEV=0 -f S32_LE -c 2 -r 16000 -d $(SECS) -t wav -' > heard.wav
+58
View File
@@ -0,0 +1,58 @@
#!/usr/bin/env node
/**
* @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 {"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.
* The key is in $CREDENTIALS_DIRECTORY/ask-key (systemd LoadCredential), not argv, where ps would show it.
*/
import { newWebSocketRpcSession } from 'capnweb';
import { readFile } from 'node:fs/promises';
import process from 'node:process';
import { text } from 'node:stream/consumers';
/**
* Ask the brain at URL the question on stdin, or tell it the conversation is over.
*
* @param {object} [io] what it reaches; the process's own, by default
* @param {string[]} [io.argv] URL CONVERSATION [end]
* @param {Record<string, string | undefined>} [io.env] for CREDENTIALS_DIRECTORY
* @param {typeof readFile} [io.read] reads the key
* @param {AsyncIterable<Uint8Array>} [io.stdin] the question
* @param {{ write(s: string): unknown }} [io.stdout] the answer goes here, as JSON lines
* @param {typeof newWebSocketRpcSession} [io.connect] opens a session with the gate at URL
*/
const main = async ({
argv = process.argv.slice(2),
env = process.env,
read = readFile,
stdin = process.stdin,
stdout = process.stdout,
connect = newWebSocketRpcSession,
} = {}) => {
const [url, conversation, verb] = argv;
const key = (await read(`${env.CREDENTIALS_DIRECTORY}/ask-key`, 'utf8')).trim();
/** @param {object} obj */
const line = (obj) => stdout.write(`${JSON.stringify(obj)}\n`);
const gate = connect(url);
try {
const asker = gate.open(key);
if (verb === 'end') {
await asker.end(conversation);
return;
}
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 }); });
line({ reply, end });
} finally {
gate[Symbol.dispose]();
}
};
main().catch((err) => {
console.error(`ask-client: ${err.message ?? err}`);
process.exitCode = 1;
});
+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)
+14
View File
@@ -0,0 +1,14 @@
#!/bin/sh
# Show the device, and refuse unless it looks like an SD card in a USB reader:
# removable, on USB, under 128 GB.
set -eu
dev=${1:?usage: card-check.sh /dev/sdX}
lsblk -o NAME,SIZE,TYPE,TRAN,RM,MODEL,MOUNTPOINTS,FSTYPE,LABEL "$dev"
rm=$(lsblk -dno RM "$dev" | tr -d ' ')
tran=$(lsblk -dno TRAN "$dev" | tr -d ' ')
size=$(lsblk -bdno SIZE "$dev" | tr -d ' ')
[ "$rm" = 1 ] || { echo "$dev isn't removable" >&2; exit 1; }
[ "$tran" = usb ] || { echo "$dev isn't on USB" >&2; exit 1; }
[ "$size" -lt 137438953472 ] || { echo "$dev is too big for an SD card" >&2; exit 1; }
+36
View File
@@ -0,0 +1,36 @@
# pdtv26-box: the box's JavaScript: the ir and look servers, and the ask client.
# npm runs here, in Nix's build sandbox, from package-lock.json; so do the tests.
# gate.js and run.js are speech's, copied in: one copy in git, and no package to share them.
# The output is plain JavaScript, the same on every architecture (allowedReferences keeps it so):
# each user supplies its own node, at lib/node_modules/pdtv26-box/*.js.
{ lib, buildNpmPackage }:
buildNpmPackage {
pname = "pdtv26-box";
version = "0.1.0";
src = lib.fileset.toSource {
root = ./.;
fileset = lib.fileset.unions [
./package.json ./package-lock.json
./ir.js ./ir.test.js ./look.js ./look.test.js
./ir-server.js ./look-server.js ./ask-client.js
];
};
postPatch = ''
cp ${../speech/gate.js} gate.js
cp ${../speech/run.js} run.js
'';
npmDepsHash = "sha256-/4+KAx3SpYssfpHDfheNziTY9fnPnjHNQo/SItPabHM=";
dontNpmBuild = true;
# The scripts' #!/usr/bin/env node stays as is: patched, it would tie the package to one node.
dontPatchShebangs = true;
npmInstallFlags = [ "--ignore-scripts" ];
doCheck = true;
checkPhase = ''
runHook preCheck
# Every file parses, the servers and client included: no test imports them.
for f in *.js; do node --check "$f"; done
node --test
runHook postCheck
'';
allowedReferences = [ ];
}
+5
View File
@@ -0,0 +1,5 @@
# The box's earcons, made by earcons.sh with sox: WAVs, built, not kept in git.
{ runCommand, sox }:
runCommand "pdtv26-earcons" { nativeBuildInputs = [ sox ]; } ''
sh ${./earcons.sh} $out
''
Executable
+29
View File
@@ -0,0 +1,29 @@
#!/bin/sh
# earcons.sh DIR: the box's earcons, told apart by contour; low and long enough for older ears.
# 16 kHz, the mics' rate: they play while the mics record, on one I2S bus.
# open C E G rising, with a little echo: a press; a conversation starts; your turn
# turn one soft G: your turn again
# gotit E C falling, short: heard you; thinking
# huh D A low: didn't catch that; your turn again
# bye G E C falling, with echo: the conversation is over
# look A A, two quick taps, like a shutter: the brain is looking through the camera
set -eu
dir=$1
mkdir -p "$dir"
tmp=$(mktemp -d)
trap 'rm -rf "$tmp"' EXIT
note() { # note NAME HZ SECONDS GAIN
sox -R -n -r 16000 -c 1 -b 16 "$tmp/$1.wav" synth "$3" sine "$2" fade q 0.005 "$3" 0.04 gain "$4"
}
note C5 523.25 0.09 -7; note E5 659.25 0.09 -7; note G5 783.99 0.09 -7
note G5soft 783.99 0.14 -11
note E5s 659.25 0.07 -9; note C5s 523.25 0.10 -9
note D4 293.66 0.12 -6; note A3 220.00 0.16 -6
note A5 880.00 0.06 -9
sox -n -r 16000 -c 1 -b 16 "$tmp/gap.wav" trim 0 0.08
sox -R "$tmp/C5.wav" "$tmp/E5.wav" "$tmp/G5.wav" "$dir/open.wav" echo 0.8 0.7 60 0.3 pad 0 0.1
sox -R "$tmp/G5soft.wav" "$dir/turn.wav" echo 0.8 0.7 60 0.3 pad 0 0.05
sox -R "$tmp/E5s.wav" "$tmp/C5s.wav" "$dir/gotit.wav" pad 0 0.05
sox -R "$tmp/D4.wav" "$tmp/A3.wav" "$dir/huh.wav" pad 0 0.05
sox -R "$tmp/G5.wav" "$tmp/E5.wav" "$tmp/C5.wav" "$dir/bye.wav" echo 0.8 0.7 60 0.3 pad 0 0.1
sox -R "$tmp/A5.wav" "$tmp/gap.wav" "$tmp/A5.wav" "$dir/look.wav" pad 0 0.05
Executable
+13
View File
@@ -0,0 +1,13 @@
#!/bin/sh
# Write an image to a card: unmount whatever the desktop mounted, dd, re-read the partitions.
# Run card-check.sh first; this one trusts its arguments.
set -eu
img=${1:?usage: flash.sh IMAGE /dev/sdX}
dev=${2:?usage: flash.sh IMAGE /dev/sdX}
lsblk -lno PATH,MOUNTPOINT "$dev" | awk 'NF == 2 { print $1 }' | while read -r part; do
udisksctl unmount -b "$part"
done
sudo dd if="$img" of="$dev" bs=4M conv=fsync status=progress
sudo partprobe "$dev"
lsblk -o NAME,SIZE,FSTYPE,LABEL "$dev"
+75
View File
@@ -0,0 +1,75 @@
#!/usr/bin/env node
/**
* @file ir-server: the ir capability over Cap'n Web, behind a gate, for the brain.
* usage: ir-server.js HOST PORT PICO [STATUS_URL]
* PICO VERB ARGS... talks to the Pico: listen SECONDS, repeat N GAP_MS CODE... (../ir-pico/pico_tty.py, its tty bound in).
* STATUS_URL, if any, is a status page, told of each send, for its count of IR presses.
* The key is in $CREDENTIALS_DIRECTORY/ir-key (systemd LoadCredential), not argv, where ps would show it.
*/
import { newWebSocketRpcSession } from 'capnweb';
import { spawn as spawnChild } from 'node:child_process';
import { readFile } from 'node:fs/promises';
import process from 'node:process';
import { WebSocketServer } from 'ws';
import { Gate } from './gate.js';
import { Ir } from './ir.js';
import { makeCommand, timed } from './run.js';
/** The lines worth logging of what the Pico printed. */
const PICO_SAID = /^(got|sent|unparsed|bad)/;
/**
* Serve the ir capability, behind a gate, at HOST:PORT.
*
* @param {object} [io] what it reaches; the process's own, by default
* @param {string[]} [io.argv] HOST PORT PICO [STATUS_URL]
* @param {Record<string, string | undefined>} [io.env] for CREDENTIALS_DIRECTORY
* @param {typeof readFile} [io.read] reads the key
* @param {typeof spawnChild} [io.spawn] runs PICO, and nothing else
* @param {typeof fetch} [io.post] reaches STATUS_URL, and nothing else
* @param {() => number} [io.now] the clock, for timing jobs
* @param {(options: import('ws').ServerOptions) => WebSocketServer} [io.listen]
* @param {typeof newWebSocketRpcSession} [io.serve] serves the gate on one connection
*/
const main = async ({
argv = process.argv.slice(2),
env = process.env,
read = readFile,
spawn = spawnChild,
post = fetch,
now = Date.now,
listen = (options) => new WebSocketServer(options),
serve = newWebSocketRpcSession,
} = {}) => {
const [host, port, pico, statusUrl] = argv;
const key = (await read(`${env.CREDENTIALS_DIRECTORY}/ir-key`, 'utf8')).trim();
/**
* Tell the status page, if any; a failure there is logged, never the send's failure.
* @param {object} event
*/
const report = (event) => {
if (!statusUrl) return;
post(`${statusUrl}/event`, {
method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ source: 'pdtv26-ir', ...event }),
}).then((res) => { if (!res.ok) console.error(`status: ${res.status}`); }, (err) => console.error(`status: ${err.message}`));
};
const ir = new Ir(async (args) => {
const out = await timed(now, `pico ${args.join(' ')}`,
async () => (await makeCommand(spawn, pico, args)('')).toString(),
(o) => o.trim().split('\n').filter((ln) => PICO_SAID.test(ln)).join('; ') || '(nothing)');
if (args[0] === 'repeat') report({ kind: 'ir', code: args.slice(3).join(' '), times: Number(args[1]) });
return out;
});
const gate = new Gate(key, ir);
const wss = listen({ host, port: Number(port), maxPayload: 64 * 1024 });
wss.on('connection', (ws, req) => {
console.log(`connection from ${req.socket.remoteAddress}`);
serve(ws, gate);
});
console.log(`ir-server: listening on ${host}:${port}`);
};
main().catch((err) => {
console.error(err);
process.exitCode = 1;
});
+124
View File
@@ -0,0 +1,124 @@
/**
* @file The ir capability: learn and send infrared remote codes through the Pico on the box's USB.
* Who can work the TV, the cable box, or anything else with an IR remote is who holds an Ir.
* @see ../ir-pico/pico_tty.py, the Pico's side
*/
import { RpcTarget } from 'capnweb';
/** Long enough to find the remote and press a button or two. */
export const MAX_LISTEN_SECONDS = 60;
/** Enough presses to step through any on-screen menu. */
export const MAX_TIMES = 20;
/** NEC codes are 4 bytes; leave room for longer ones. Samsung's carry its name. */
const CODE = /^(samsung )?[0-9A-F]{2}( [0-9A-F]{2}){0,15}$/;
/** Pulses the Pico keeps of a burst (ir_commands.MAX_RAW). */
export const MAX_RAW = 199;
/** Any other remote's burst: mark and space lengths in microseconds, mark first and last. */
const RAW = /^raw [1-9][0-9]{0,4}( [1-9][0-9]{0,4})*$/;
/** @param {string} code */
const isRaw = (code) => {
if (!RAW.test(code)) return false;
const us = code.split(' ').slice(1).map(Number);
return us.length % 2 === 1 && us.length <= MAX_RAW && us.every((n) => n <= 65535);
};
/**
* Two raw frames of one button: as many pulses, each within a fifth.
* @param {string} a
* @param {string} b
*/
const sameRaw = (a, b) => {
const [as, bs] = [a.split(' '), b.split(' ')];
return as.length === bs.length
&& as.every((x, i) => i === 0 || Math.abs(+x - +bs[i]) <= 0.2 * Math.max(+x, +bs[i]));
};
/**
* "Samsung e0 e0 40 bf" => "samsung E0 E0 40 BF": names in lower case, bytes in upper.
* @param {string} code
*/
const normalize = (code) =>
code.trim().split(/\s+/).map((w) => (/^[a-z]{3,}$/i.test(w) ? w.toLowerCase() : w.toUpperCase())).join(' ');
/**
* Sort what the Pico printed: "got 20 DF 10 EF" is a code it decoded (NEC;
* Samsung's come named: "got samsung E0 E0 40 BF"); any other remote's comes raw,
* "got raw 2400 600 1200 ...", and a held button's run of raw frames counts once;
* "unparsed: ..." is a burst too short to be a code (noise).
* @param {string} out
* @returns {{ codes: string[], unparsed: string[] }}
*/
export const parseHeard = (out) => {
const lines = out.split('\n').map((ln) => ln.trim());
/** @type {string[]} */
const codes = [];
for (const code of lines.filter((ln) => ln.startsWith('got ')).map((ln) => ln.slice(4))) {
const prev = codes.at(-1);
if (!(prev?.startsWith('raw ') && code.startsWith('raw ') && sameRaw(prev, code))) codes.push(code);
}
return { codes, unparsed: lines.filter((ln) => ln.startsWith('unparsed:')) };
};
/**
* listen(seconds) reports the codes a remote sent meanwhile; send(code, times, gapMs) sends one,
* times times, gapMs apart: quick enough that a TV's input menu stays open between presses.
* One at a time: there's one Pico, and listening while sending hears our own echo.
*/
export class Ir extends RpcTarget {
#pico;
/** @type {Promise<unknown>} the job before this one */
#last = Promise.resolve();
/** @param {(args: string[]) => Promise<string>} pico runs pico_tty.py's verbs: listen SECONDS, repeat N GAP_MS CODE... */
constructor(pico) {
super();
this.#pico = pico;
}
/**
* @template T
* @param {() => Promise<T>} job
* @returns {Promise<T>}
*/
#inTurn(job) {
const result = this.#last.then(job);
this.#last = result.catch(() => {});
return result;
}
/** @param {number} seconds */
listen(seconds) {
if (!Number.isInteger(seconds) || seconds < 1 || seconds > MAX_LISTEN_SECONDS) {
throw new RangeError(`seconds: a whole number, 1 to ${MAX_LISTEN_SECONDS}`);
}
return this.#inTurn(async () => parseHeard(await this.#pico(['listen', String(seconds)])));
}
/**
* @param {string} code as listen reports it: hex bytes, "20 DF 10 EF" or "samsung E0 E0 40 BF",
* or pulses, "raw 2400 600 1200 ..." (sent as a short press: three frames)
* @param {number} [times] presses, 1 to MAX_TIMES
* @param {number} [gapMs] between presses, 100 to 2000
*/
send(code, times = 1, gapMs = 400) {
const norm = typeof code === 'string' ? normalize(code) : '';
if (!CODE.test(norm) && !isRaw(norm)) {
throw new TypeError(`code: hex bytes, like "20 DF 10 EF" or "samsung E0 E0 40 BF"; or "raw" and an odd number of microseconds, up to ${MAX_RAW}, each up to 65535`);
}
if (!Number.isInteger(times) || times < 1 || times > MAX_TIMES) {
throw new RangeError(`times: a whole number, 1 to ${MAX_TIMES}`);
}
if (!Number.isInteger(gapMs) || gapMs < 100 || gapMs > 2000) throw new RangeError('gapMs: 100 to 2000');
return this.#inTurn(async () => {
const out = await this.#pico(['repeat', String(times), String(gapMs), ...norm.split(' ')]);
const sent = out.split('\n').filter((ln) => ln.trim() === `sent ${norm}`).length;
if (sent < times) throw new Error(`the Pico confirmed ${sent} of ${times}: ${out.trim().slice(-200)}`);
return times === 1 ? `sent ${norm}` : `sent ${norm} ${times} times, ${gapMs} ms apart`;
});
}
}
+101
View File
@@ -0,0 +1,101 @@
// Tests for the ir capability, with a fake Pico: no serial port.
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { Ir, parseHeard } from './ir.js';
test('listen sorts decoded codes from unparsed bursts', async () => {
const calls = [];
const ir = new Ir(async (args) => {
calls.push(args);
return 'ir-pico ready\ngot 20 DF 10 EF\r\nunparsed: 3 12 pulses\ngot 20 DF 40 BF\n';
});
assert.deepEqual(await ir.listen(10), {
codes: ['20 DF 10 EF', '20 DF 40 BF'],
unparsed: ['unparsed: 3 12 pulses'],
});
assert.deepEqual(calls, [['listen', '10']]);
});
test('listen takes a whole number of seconds, within reason', () => {
const ir = new Ir(async () => '');
for (const bad of [0, 61, 1.5, '10', undefined]) assert.throws(() => ir.listen(bad), /seconds/);
});
test('send normalizes the code and wants the Pico to confirm each press', async () => {
const calls = [];
const ir = new Ir(async (args) => {
calls.push(args);
const [, times, , ...octets] = args;
return octets.includes('EF') ? `sent ${octets.join(' ')}\n`.repeat(Number(times)) : 'bad code\n';
});
assert.equal(await ir.send(' 20 df 10 ef '), 'sent 20 DF 10 EF');
assert.deepEqual(calls, [['repeat', '1', '400', '20', 'DF', '10', 'EF']]);
await assert.rejects(ir.send('20 DF 10 EE'), /confirmed 0 of 1/);
});
test('send presses a button several times, quickly enough for a menu', async () => {
const calls = [];
const ir = new Ir(async (args) => {
calls.push(args);
return 'sent 20 DF F4 0B\n'.repeat(args[1] === '5' ? 3 : Number(args[1]));
});
assert.equal(await ir.send('20 DF F4 0B', 3, 300), 'sent 20 DF F4 0B 3 times, 300 ms apart');
assert.deepEqual(calls, [['repeat', '3', '300', '20', 'DF', 'F4', '0B']]);
await assert.rejects(ir.send('20 DF F4 0B', 5), /confirmed 3 of 5/);
for (const bad of [0, 21, 1.5, '3']) assert.throws(() => ir.send('20 DF F4 0B', bad), /times/);
for (const bad of [50, 2001]) assert.throws(() => ir.send('20 DF F4 0B', 2, bad), /gapMs/);
});
test('Samsung codes carry their name, there and back', async () => {
const calls = [];
const ir = new Ir(async (args) => {
calls.push(args);
return args[0] === 'listen' ? 'got samsung E0 E0 67 98\n' : `sent ${args.slice(3).join(' ')}\n`;
});
assert.deepEqual(await ir.listen(5), { codes: ['samsung E0 E0 67 98'], unparsed: [] });
assert.equal(await ir.send('Samsung e0 e0 67 98'), 'sent samsung E0 E0 67 98');
assert.deepEqual(calls[1], ['repeat', '1', '400', 'samsung', 'E0', 'E0', '67', '98']);
for (const bad of ['sony 01 02', 'samsung', '20 samsung DF']) assert.throws(() => ir.send(bad), /hex bytes/);
});
test('other remotes come raw: a held button counts once, and goes back as heard', async () => {
const sony = 'raw 2400 600 1200 600 600 600 1200';
const calls = [];
const ir = new Ir(async (args) => {
calls.push(args);
return args[0] === 'listen'
? `got ${sony}\ngot raw 2380 610 1210 590 600 600 1190\ngot raw 2400 600 600 600 600 600 1200\nunparsed: Too short 3 pulses\n`
: `sent ${args.slice(3).join(' ')}\n`;
});
assert.deepEqual(await ir.listen(5), {
codes: [sony, 'raw 2400 600 600 600 600 600 1200'],
unparsed: ['unparsed: Too short 3 pulses'],
});
assert.equal(await ir.send(`RAW ${sony.slice(4)}`), `sent ${sony}`);
assert.deepEqual(calls[1], ['repeat', '1', '400', ...sony.split(' ')]);
const long = `raw ${Array(201).fill('600').join(' ')}`;
for (const bad of ['raw', 'raw 2400 600', 'raw 70000', 'raw 0600', 'raw 2400 6e2 600', long]) {
assert.throws(() => ir.send(bad), /microseconds/);
}
});
test('send refuses what is not hex bytes', () => {
const ir = new Ir(async () => '');
for (const bad of ['', 'power', '2 DF', '20DF10EF', '20; rm', 32]) assert.throws(() => ir.send(bad), /hex bytes/);
});
test('one at a time: a send waits for a listen to finish', async () => {
const log = [];
const ir = new Ir(async ([verb, ...rest]) => {
log.push(`start ${verb}`);
await new Promise((r) => setTimeout(r, 10));
log.push(`end ${verb}`);
return verb === 'repeat' ? `sent ${rest.slice(2).join(' ')}` : '';
});
await Promise.all([ir.listen(1), ir.send('20 DF 10 EF')]);
assert.deepEqual(log, ['start listen', 'end listen', 'start repeat', 'end repeat']);
});
test('parseHeard of nothing', () => {
assert.deepEqual(parseHeard(''), { codes: [], unparsed: [] });
});
+81
View File
@@ -0,0 +1,81 @@
#!/usr/bin/env node
/**
* @file look-server: the look capability over Cap'n Web, behind a gate, for the brain.
* usage: look-server.js HOST PORT SIGNAL_SOCKET FFMPEG
* SIGNAL_SOCKET is the button service's: while a connection to it is open, the box shows it's looking.
* The key is in $CREDENTIALS_DIRECTORY/look-key, and the camera's RTSP URL, password and all,
* in $CREDENTIALS_DIRECTORY/rtsp-url (systemd LoadCredential).
*/
import { newWebSocketRpcSession } from 'capnweb';
import { spawn as spawnChild } from 'node:child_process';
import { readFile } from 'node:fs/promises';
import { createConnection } from 'node:net';
import process from 'node:process';
import { WebSocketServer } from 'ws';
import { Gate } from './gate.js';
import { Look } from './look.js';
import { makeCommand, timed } from './run.js';
/**
* Connect to the button service and wait for "looking"; resolve to a function that ends the connection.
*
* @param {() => import('node:net').Socket} connect opens a connection to the button service's socket, and no other
*/
const signalVia = (connect) => () => new Promise((resolve, reject) => {
const conn = connect();
/** @param {Error} err */
const fail = (err) => { conn.destroy(); reject(new Error(`the box can't show it's looking: ${err.message}`)); };
conn.setTimeout(5000, () => fail(new Error('no answer in 5 s')));
conn.on('error', fail);
conn.on('data', (d) => {
if (!d.toString().startsWith('looking')) return;
conn.setTimeout(0);
resolve(() => conn.end());
});
});
/**
* Serve the look capability, behind a gate, at HOST:PORT.
*
* @param {object} [io] what it reaches; the process's own, by default
* @param {string[]} [io.argv] HOST PORT SIGNAL_SOCKET FFMPEG
* @param {Record<string, string | undefined>} [io.env] for CREDENTIALS_DIRECTORY
* @param {typeof readFile} [io.read] reads the key and the camera's URL
* @param {typeof spawnChild} [io.spawn] runs FFMPEG, and nothing else
* @param {typeof createConnection} [io.connect] reaches SIGNAL_SOCKET, and nothing else
* @param {() => number} [io.now] the clock, for timing looks
* @param {(options: import('ws').ServerOptions) => WebSocketServer} [io.listen]
* @param {typeof newWebSocketRpcSession} [io.serve] serves the gate on one connection
*/
const main = async ({
argv = process.argv.slice(2),
env = process.env,
read = readFile,
spawn = spawnChild,
connect = createConnection,
now = Date.now,
listen = (options) => new WebSocketServer(options),
serve = newWebSocketRpcSession,
} = {}) => {
const [host, port, socketPath, ffmpeg] = argv;
/** @param {string} name */
const cred = async (name) => (await read(`${env.CREDENTIALS_DIRECTORY}/${name}`, 'utf8')).trim();
const [key, url] = [await cred('look-key'), await cred('rtsp-url')];
// One frame, 1280 wide: plenty to read a TV screen, and fewer tokens than 1920.
const grabOne = makeCommand(spawn, ffmpeg, ['-v', 'error', '-rtsp_transport', 'tcp', '-timeout', '10000000',
'-i', url, '-frames:v', '1', '-vf', 'scale=1280:-2', '-q:v', '4', '-f', 'image2pipe', '-c:v', 'mjpeg', '-']);
const look = new Look(signalVia(() => connect(socketPath)),
() => timed(now, 'look', () => grabOne(''), (jpeg) => `${jpeg.length} bytes`));
const gate = new Gate(key, look);
const wss = listen({ host, port: Number(port), maxPayload: 64 * 1024 });
wss.on('connection', (ws, req) => {
console.log(`connection from ${req.socket.remoteAddress}`);
serve(ws, gate);
});
console.log(`look-server: listening on ${host}:${port}`);
};
main().catch((err) => {
console.error(err);
process.exitCode = 1;
});
+41
View File
@@ -0,0 +1,41 @@
/**
* @file The look capability: one still frame from a camera aimed at the TV.
* Who can see the room is who holds a Look. The box shows every look, with a tap and a flash
* (body/look_signal.py): no indication, no look.
*/
import { RpcTarget } from 'capnweb';
/**
* look() returns one frame, a JPEG in base64, taken while the box shows it's looking.
* One at a time: one camera.
*/
export class Look extends RpcTarget {
#signal;
#grab;
/** @type {Promise<unknown>} the look before this one */
#last = Promise.resolve();
/**
* @param {() => Promise<() => void>} signal has the box show it's looking; resolves, once it is, to a function that stops it
* @param {() => Promise<Uint8Array>} grab one frame from the camera, as JPEG
*/
constructor(signal, grab) {
super();
this.#signal = signal;
this.#grab = grab;
}
look() {
const job = async () => {
const stop = await this.#signal();
try {
return Buffer.from(await this.#grab()).toString('base64');
} finally {
stop();
}
};
const result = this.#last.then(job);
this.#last = result.catch(() => {});
return result;
}
}
+43
View File
@@ -0,0 +1,43 @@
// Tests for the look capability, with a fake camera and a fake button service.
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { Look } from './look.js';
const fakes = ({ signalFails = false, grabFails = false } = {}) => {
const log = [];
const signal = async () => {
if (signalFails) throw new Error('the button service is not listening');
log.push('flash');
return () => log.push('stop');
};
const grab = async () => {
log.push('grab');
if (grabFails) throw new Error('camera: 401');
return new Uint8Array([0xff, 0xd8, 0xff]);
};
return { log, look: new Look(signal, grab) };
};
test('a look is shown before the frame is taken, and stops after', async () => {
const { log, look } = fakes();
assert.equal(await look.look(), '/9j/');
assert.deepEqual(log, ['flash', 'grab', 'stop']);
});
test('no indication, no look', async () => {
const { log, look } = fakes({ signalFails: true });
await assert.rejects(look.look(), /not listening/);
assert.deepEqual(log, []);
});
test('the indication stops even when the camera fails', async () => {
const { log, look } = fakes({ grabFails: true });
await assert.rejects(look.look(), /401/);
assert.deepEqual(log, ['flash', 'grab', 'stop']);
});
test('one look at a time', async () => {
const { log, look } = fakes();
await Promise.all([look.look(), look.look()]);
assert.deepEqual(log, ['flash', 'grab', 'stop', 'flash', 'grab', 'stop']);
});
+172
View File
@@ -0,0 +1,172 @@
# The box's services: the button, and the ir and look capabilities for the brain.
# Each runs with only the devices and addresses it needs. Keys and the camera's URL live in
# /etc/pdtv26, root's alone (make keys); systemd hands each service a copy (LoadCredential).
{ config, lib, pkgs, ... }:
let
cfg = config.pdtv26.box;
inherit (lib) mkOption mkEnableOption mkIf mkDefault types;
keys = "/etc/pdtv26";
node = "${pkgs.nodejs-slim}/bin/node";
boxJs = "${cfg.packages.boxJs}/lib/node_modules/pdtv26-box";
speechJs = "${cfg.packages.speechJs}/lib/node_modules/pdtv26-speech";
script = name: path: pkgs.writeShellScript name ''exec ${node} ${path} "$@"'';
# What every service gets: no new privileges, a read-only system, no homes, its own /tmp.
confined = {
Restart = "on-failure";
RestartSec = 5;
NoNewPrivileges = true;
ProtectSystem = "strict";
ProtectHome = true;
PrivateTmp = true;
IPAddressDeny = "any";
RestrictAddressFamilies = [ "AF_INET" "AF_INET6" "AF_UNIX" ];
};
in
{
options.pdtv26.box = {
enable = mkEnableOption "the box's button, ir, and look services";
speechUrl = mkOption {
type = types.str;
example = "ws://home:8024/";
description = "The speech capability's server: the box's ears and voice.";
};
askUrl = mkOption {
type = types.str;
example = "ws://home:8025/";
description = "The brain's ask capability.";
};
statusUrl = mkOption {
type = types.nullOr types.str;
default = null;
example = "http://home:8027";
description = "A status page, told of each conversation, look, and IR press, with a heartbeat; on the private network.";
};
ports = {
ir = mkOption { type = types.port; default = 8026; description = "Where the ir capability listens."; };
look = mkOption { type = types.port; default = 8028; description = "Where the look capability listens."; };
};
network = {
interface = mkOption {
type = types.str;
default = "tailscale0";
description = "The private network's interface, where the brain reaches ir and look.";
};
ranges = mkOption {
type = types.listOf types.str;
default = [ "100.64.0.0/10" "fd7a:115c:a1e0::/48" ]; # a tailnet's, MagicDNS (100.100.100.100) included
description = "The private network's addresses: the only ones the box's services reach, or answer.";
};
};
look = {
enable = mkEnableOption "the look capability: one frame from a camera on the LAN, aimed at the TV" // { default = true; };
ranges = mkOption {
type = types.listOf types.str;
default = [ "10.0.0.0/8" "172.16.0.0/12" "192.168.0.0/16" ];
description = "Where the camera may be: look reaches these, besides the private network.";
};
};
packages = {
speechJs = mkOption { type = types.package; default = pkgs.callPackage ../speech/default.nix { }; description = "The speech clients."; };
boxJs = mkOption { type = types.package; default = pkgs.callPackage ./default.nix { }; description = "The ir and look servers, and the ask client."; };
earcons = mkOption { type = types.package; default = pkgs.callPackage ./earcons.nix { }; description = "The chimes that say whose turn it is."; };
};
};
config = mkIf cfg.enable {
services.tailscale.enable = mkDefault (cfg.network.interface == "tailscale0");
networking.firewall.interfaces.${cfg.network.interface}.allowedTCPPorts =
[ cfg.ports.ir ] ++ lib.optional cfg.look.enable cfg.ports.look;
# GPIO access is per chip, not per line: the gpio group gets gpiochip0, and only the button user is in it.
# Lines the kernel holds (the amp's SD_MODE on 16) stay busy; the button service requests 23 and 25 alone.
# The Pico, under CircuitPython, by its USB IDs: its console (interface 0) is /dev/pdtv26-ir.
users.groups.gpio = { };
services.udev.extraRules = ''
SUBSYSTEM=="gpio", KERNEL=="gpiochip0", GROUP="gpio", MODE="0660"
SUBSYSTEM=="tty", ATTRS{idVendor}=="239a", ATTRS{idProduct}=="80f4", ENV{ID_USB_INTERFACE_NUM}=="00", SYMLINK+="pdtv26-ir"
'';
# The button: a press starts a conversation; turns are by voice, a press interrupts (body/box.py).
users.users.button = { isSystemUser = true; group = "button"; extraGroups = [ "gpio" "audio" ]; };
users.groups.button = { };
# look-server connects here to say it's looking; the button service taps and flashes while it does.
# The socket's group is the whole of who may: look-server, and no one else.
users.groups.look-signal = { };
systemd.sockets.pdtv26-button = {
wantedBy = [ "sockets.target" ];
socketConfig = {
ListenStream = "/run/pdtv26-look.sock";
SocketUser = "button";
SocketGroup = "look-signal";
SocketMode = "0660";
};
};
systemd.services.pdtv26-button = {
description = "the box's button: press and talk";
wantedBy = [ "multi-user.target" ];
requires = [ "pdtv26-button.socket" ];
after = [ "pdtv26-button.socket" ];
serviceConfig = confined // {
User = "button";
StateDirectory = "pdtv26-button";
StateDirectoryMode = "0700";
LoadCredential = [ "speech-key:${keys}/speech-key" "ask-key:${keys}/ask-key" ];
# -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"
(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
cfg.packages.earcons "/var/lib/pdtv26-button"
] + lib.optionalString (cfg.statusUrl != null) " ${lib.escapeShellArg cfg.statusUrl}";
# The private network alone: enough to reach speech and the brain, and nothing else.
IPAddressAllow = cfg.network.ranges;
DevicePolicy = "closed";
DeviceAllow = [ "/dev/gpiochip0 rw" "char-alsa rw" ];
};
};
# The ir capability: learn and send IR codes through the Pico (../ir-pico), for the brain.
# DeviceAllow's char-ttyACM is looked up in /proc/devices when the service starts; without cdc_acm loaded
# by then (it loads when the Pico enumerates, maybe after boot starts the service), the tty gets EPERM.
boot.kernelModules = [ "cdc_acm" ];
systemd.services.pdtv26-ir = {
description = "the box's IR remote, as a capability";
wantedBy = [ "multi-user.target" ];
serviceConfig = confined // {
DynamicUser = true;
SupplementaryGroups = [ "dialout" ];
LoadCredential = [ "ir-key:${keys}/ir-key" ];
ExecStart =
let pico = pkgs.writeShellScript "pico" ''
exec ${pkgs.python3.withPackages (ps: [ ps.pyserial ])}/bin/python3 -I ${../ir-pico/pico_tty.py} /dev/pdtv26-ir "$@"
'';
in lib.escapeShellArgs ([ node "${boxJs}/ir-server.js" "::" (toString cfg.ports.ir) pico ]
++ lib.optional (cfg.statusUrl != null) cfg.statusUrl);
IPAddressAllow = [ "localhost" ] ++ cfg.network.ranges;
DevicePolicy = "closed";
DeviceAllow = [ "char-ttyACM rw" ];
};
};
# The look capability: one frame from the camera aimed at the TV (../look.js), for the brain.
# It reaches the camera on the LAN and the button service's socket, and won't look unless the button shows it.
systemd.services.pdtv26-look = mkIf cfg.look.enable {
description = "the box's eyes, as a capability";
wantedBy = [ "multi-user.target" ];
after = [ "pdtv26-button.socket" ];
serviceConfig = confined // {
DynamicUser = true;
SupplementaryGroups = [ "look-signal" ];
# rtsp-url: the camera's stream, password and all.
LoadCredential = [ "look-key:${keys}/look-key" "rtsp-url:${keys}/rtsp-url" ];
ExecStart = lib.escapeShellArgs [ node "${boxJs}/look-server.js" "::" (toString cfg.ports.look)
"/run/pdtv26-look.sock" "${pkgs.ffmpeg-headless}/bin/ffmpeg" ];
PrivateDevices = true;
IPAddressAllow = [ "localhost" ] ++ cfg.network.ranges ++ cfg.look.ranges;
MemoryMax = "300M";
};
};
};
}
+44
View File
@@ -0,0 +1,44 @@
{
"name": "pdtv26-box",
"version": "0.1.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "pdtv26-box",
"version": "0.1.0",
"license": "Apache-2.0",
"dependencies": {
"capnweb": "0.13.1",
"ws": "8.23.1"
}
},
"node_modules/capnweb": {
"version": "0.13.1",
"resolved": "https://registry.npmjs.org/capnweb/-/capnweb-0.13.1.tgz",
"integrity": "sha512-JEE/MYKv41blYv5MGGzKiT3DT4qz00AQ+NsmPSdVFVSKuy2/ggUI4aDGJO+jEvAXNXuZURoxo7hCfx+VKbM32g==",
"license": "MIT"
},
"node_modules/ws": {
"version": "8.23.1",
"resolved": "https://registry.npmjs.org/ws/-/ws-8.23.1.tgz",
"integrity": "sha512-1rzWDSN0NOi3tpwgHsQExjWRoKUGtjCkJ2gZRaaRtzhYLboMytOI9pj9PU7yCgY37auqdd4OyLofZDbkeuZmPA==",
"license": "MIT",
"engines": {
"node": ">=10.0.0"
},
"peerDependencies": {
"bufferutil": "^4.0.1",
"utf-8-validate": ">=5.0.2"
},
"peerDependenciesMeta": {
"bufferutil": {
"optional": true
},
"utf-8-validate": {
"optional": true
}
}
}
}
}
+15
View File
@@ -0,0 +1,15 @@
{
"name": "pdtv26-box",
"version": "0.1.0",
"description": "The box's capabilities for the agent at the TV: ir and look, over Cap'n Web; and its ask client",
"private": true,
"type": "module",
"license": "Apache-2.0",
"scripts": {
"test": "node --test"
},
"dependencies": {
"capnweb": "0.13.1",
"ws": "8.23.1"
}
}
+49
View File
@@ -0,0 +1,49 @@
# A box's whole system, from a few names: what lib.mkBox adds to the box's services.
# name the box's host name
# server the home server's name, where speech and the brain listen
# wifi the Wi-Fi network the box joins; its PSK goes on the card after imaging (make wifi-secret)
# admin who looks after the box, and logs in with sshKeys to deploy
{ name, server, wifi, admin, sshKeys }:
{ config, pkgs, ... }:
{
networking.hostName = name;
hardware.enableRedistributableFirmware = true; # the Pi 3B's Wi-Fi (brcmfmac)
pdtv26.box = {
enable = true;
speechUrl = "ws://${server}:8024/";
askUrl = "ws://${server}:8025/";
};
# Wi-Fi: the PSK stays out of the Nix store (it's world-readable).
networking.wireless = {
enable = true;
secretsFile = "/etc/wifi-secrets";
networks.${wifi}.pskRaw = "ext:psk";
};
# wpa_supplicant runs as its own user; its group number exists only after the first boot.
systemd.tmpfiles.rules = [ "z /etc/wifi-secrets 0640 root wpa_supplicant -" ];
services.avahi = { enable = true; nssmdns4 = true; publish = { enable = true; addresses = true; }; };
services.openssh = {
enable = true;
settings = { PasswordAuthentication = false; KbdInteractiveAuthentication = false; PermitRootLogin = "no"; };
};
users.users.${admin} = {
isNormalUser = true;
extraGroups = [ "wheel" "dialout" "audio" ]; # dialout: the Pico's serial port; audio: the Voice HAT
openssh.authorizedKeys.keys = sshKeys;
};
security.sudo.wheelNeedsPassword = false; # keys only; nixos-rebuild --target-host needs sudo
nix.settings.trusted-users = [ "@wheel" ];
nix.settings.experimental-features = [ "nix-command" "flakes" ];
zramSwap.enable = true; # 1 GB of RAM
boot.zfs.forceImportRoot = false; # no ZFS here; the 26.11 default, and quiet now
sdImage.compressImage = false;
# For make say, volume, and record, over ssh.
environment.systemPackages = [ pkgs.alsa-utils pkgs.espeak-ng ];
environment.etc."pdtv26-earcons".source = config.pdtv26.box.packages.earcons;
system.stateVersion = "26.05";
}
+79
View File
@@ -0,0 +1,79 @@
# The Google AIY Voice Kit v1's HAT on a Raspberry Pi 3B: its speaker and mics, on one I2S bus:
# a MAX98357A amp (out, GPIO 21) and two ICS-43432 mics (in, GPIO 20). Mainline Linux has no
# googlevoicehat driver, but the codecs and simple-audio-card do the same; SD_MODE on GPIO 16, as in
# Google's overlay. simple-audio-card takes one codec per link, so the card gets two links on the
# same I2S: device 0 plays, device 1 records. The direction flags go on the codec nodes: simple-card
# reads them from the link, cpu, then codec, and the last one read wins.
{ ... }:
{
hardware.deviceTree.overlays = [{
name = "voicehat";
dtsText = ''
/dts-v1/;
/plugin/;
/ {
compatible = "brcm,bcm2837";
fragment@0 {
target = <&gpio>;
__overlay__ {
voicehat_i2s_pins: voicehat_i2s_pins { brcm,pins = <18 19 20 21>; brcm,function = <4>; }; /* ALT0 */
};
};
fragment@1 {
target = <&i2s>;
/* mainline's i2s node lacks #sound-dai-cells; without it simple-audio-card fails with -EINVAL */
__overlay__ { pinctrl-names = "default"; pinctrl-0 = <&voicehat_i2s_pins>; #sound-dai-cells = <0>; status = "okay"; };
};
fragment@2 {
target-path = "/";
__overlay__ {
voicehat_amp: voicehat-amp {
compatible = "maxim,max98357a";
#sound-dai-cells = <0>;
sdmode-gpios = <&gpio 16 0>;
};
voicehat_mic: voicehat-mic {
compatible = "invensense,ics43432";
#sound-dai-cells = <0>;
};
voicehat-sound {
compatible = "simple-audio-card";
simple-audio-card,name = "voicehat";
#address-cells = <1>;
#size-cells = <0>;
simple-audio-card,dai-link@0 {
reg = <0>;
format = "i2s";
cpu { sound-dai = <&i2s>; };
codec { sound-dai = <&voicehat_amp>; playback-only; };
};
simple-audio-card,dai-link@1 {
reg = <1>;
format = "i2s";
cpu { sound-dai = <&i2s>; };
codec { sound-dai = <&voicehat_mic>; capture-only; };
};
};
};
};
};
'';
}];
# 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.
hardware.alsa = {
enable = true;
enablePersistence = true;
# The card numbers its links in reverse of the overlay's order: device 0 is the mics, 1 the amp.
# The amp and mics share one I2S bus, so they run together only in one format: the mics'.
# Whichever opens first sets it; so the amp always asks for 32-bit stereo at 16 kHz.
config = ''
pcm.voicehat_out {
type plug
slave { pcm "hw:CARD=voicehat,DEV=1"; format S32_LE; rate 16000; channels 2; }
}
'';
controls.speaker = { device = "voicehat_out"; card = "voicehat"; };
};
}
+18
View File
@@ -0,0 +1,18 @@
#!/bin/sh
# Put a Wi-Fi network's PSK on the card's root, for networking.wireless.secretsFile.
# The passphrase comes from the desktop keyring and goes no further than wifi_psk.py;
# only the PSK goes on the card. To keep it there, once:
# secret-tool store --label="Wi-Fi SSID" service wifi ssid SSID
set -eu
ssid=${1:?usage: wifi-secret.sh SSID MOUNTPOINT}
mnt=${2:?usage: wifi-secret.sh SSID MOUNTPOINT}
here=$(dirname "$0")
sudo mkdir -p "$mnt"
mountpoint -q "$mnt" || sudo mount /dev/disk/by-label/NIXOS_SD "$mnt"
trap 'sudo umount "$mnt"' EXIT
secret-tool lookup service wifi ssid "$ssid" \
| python3 -I "$here/wifi_psk.py" "$ssid" psk \
| sudo install -D -m 640 /dev/stdin "$mnt/etc/wifi-secrets"
sudo grep -c '^psk=[0-9a-f]\{64\}$' "$mnt/etc/wifi-secrets"
+36
View File
@@ -0,0 +1,36 @@
#!/usr/bin/env python3
r"""Print a Wi-Fi network's WPA PSK for wpa_supplicant, from the passphrase on stdin.
Usage: wifi_psk.py SSID NAME < passphrase
prints NAME=<64 hex digits>, a line for networking.wireless.secretsFile.
The passphrase never goes on argv, and the box gets only the PSK. wpa_passphrase
does the same, but won't read from a pipe (tcgetattr fails).
>>> psk('IEEE', 'password') # IEEE 802.11i, H.4.1 test vector
'f42c6fc52df0ebef9ebb4b90b38a5f902e83fe1b135a70e23aed762e9710a12e'
"""
import hashlib
def psk(ssid, passphrase):
"""WPA PSK: PBKDF2-HMAC-SHA1, salted by the SSID, 4096 rounds, 32 bytes."""
return hashlib.pbkdf2_hmac('sha1', passphrase.encode(), ssid.encode(), 4096, 32).hex()
def main(argv, stdin, stdout):
[_, ssid, name] = argv
passphrase = stdin.read().rstrip('\n')
if not 8 <= len(passphrase) <= 63:
raise SystemExit('a WPA passphrase is 8 to 63 characters')
stdout.write(f'{name}={psk(ssid, passphrase)}\n')
if __name__ == '__main__':
def _script_io():
from sys import argv, stdin, stdout
main(list(argv), stdin, stdout)
_script_io()
+42 -2
View File
@@ -7,18 +7,46 @@
let
systems = [ "x86_64-linux" "aarch64-linux" ];
forAll = f: nixpkgs.lib.genAttrs systems (system: f nixpkgs.legacyPackages.${system});
python = pkgs: pkgs.python3.withPackages (ps: [ ps.pyserial ]);
python = pkgs: pkgs.python3.withPackages (ps: [ ps.pyserial ps.libgpiod ps.pyflakes ]);
# An example box, for nix flake check: does a box's system evaluate?
example = self.lib.mkBox {
name = "box"; server = "home"; wifi = "home"; admin = "admin"; sshKeys = [ ];
};
in
{
# The box's services, for a NixOS system of your own.
nixosModules.box = ./box/module.nix;
# A box: a Raspberry Pi 3B with the AIY Voice HAT, from a few names (box/system.nix says which).
# Its image: (mkBox { ... }).config.system.build.sdImage. The box's JavaScript and earcons are
# the same on every architecture, so they're built natively, on buildSystem, rather than under qemu.
lib.mkBox = { name, server, wifi, admin, sshKeys, modules ? [ ], buildSystem ? "x86_64-linux" }:
nixpkgs.lib.nixosSystem {
system = "aarch64-linux";
modules = [
"${nixpkgs}/nixos/modules/installer/sd-card/sd-image-aarch64.nix"
self.nixosModules.box
./box/voicehat.nix
(import ./box/system.nix { inherit name server wifi admin sshKeys; })
{
pdtv26.box.packages = with self.packages.${buildSystem}; {
speechJs = speech-js; boxJs = box-js; inherit earcons;
};
}
] ++ modules;
};
packages = forAll (pkgs: {
speech = pkgs.callPackage ./speech/server.nix { };
speech-js = pkgs.callPackage ./speech/default.nix { };
box-js = pkgs.callPackage ./box/default.nix { };
earcons = pkgs.callPackage ./box/earcons.nix { };
});
# nix develop --command make test
devShells = forAll (pkgs: {
default = pkgs.mkShellNoCC {
packages = [ (python pkgs) pkgs.gnumake pkgs.gawk pkgs.curl pkgs.picocom ];
packages = [ (python pkgs) pkgs.gnumake pkgs.gawk pkgs.curl pkgs.picocom pkgs.nixos-rebuild pkgs.libsecret ];
};
});
@@ -29,6 +57,18 @@
touch $out
'';
speech = self.packages.${pkgs.stdenv.hostPlatform.system}.speech-js;
box-js = self.packages.${pkgs.stdenv.hostPlatform.system}.box-js;
# Doctests, and pyflakes for the names doctests don't reach.
box-py = pkgs.runCommand "box-py-doctests" { nativeBuildInputs = [ (python pkgs) ]; } ''
cd ${./box/body}
python3 -I -m doctest *.py
pyflakes *.py ${./box/wifi_psk.py}
python3 -I -m doctest ${./box/wifi_psk.py}
touch $out
'';
# The example box's system evaluates; building it takes aarch64, and booting it, a Pi.
box-system = pkgs.writeText "box-system"
(builtins.unsafeDiscardStringContext example.config.system.build.toplevel.drvPath);
});
};
}