Compare commits
7
Commits
4dfff77b95
..
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f50c871521 | ||
|
|
5191ee9931 | ||
|
|
cf503ac247 | ||
|
|
f3f2c8966e | ||
|
|
9b85deca8f | ||
|
|
5cbea49349 | ||
|
|
190600a696 |
No files matched your search
@@ -3,5 +3,4 @@ __pycache__/
|
|||||||
ir-pico/cache/
|
ir-pico/cache/
|
||||||
speech/cache/
|
speech/cache/
|
||||||
node_modules/
|
node_modules/
|
||||||
box/image
|
|
||||||
box/heard.wav
|
box/heard.wav
|
||||||
+1
-1
@@ -29,7 +29,7 @@ The connections are [Cap'n Web](https://github.com/cloudflare/capnweb) over WebS
|
|||||||
|
|
||||||
### Confinement
|
### 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.
|
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. Likewise the button service can't send IR codes: for each conversation it holds a connection to `ir`'s socket, whose group is the button's alone, and `ir` mutes the TV meanwhile if the brain turned that on. [box/module.nix](box/module.nix) has the details.
|
||||||
|
|
||||||
The brain runs in [bwrap](brain/brain.service): a read-only system, an empty home directory except for its workspace, its channel's keys (read-only), and the claude binary; its own source is in the Nix store, read-only, so it can read how it works. The systemd and D-Bus sockets, the ssh and gpg agents, and X are hidden. The network is not yet confined: it needs its model's API, but today it could also reach the home network.
|
The brain runs in [bwrap](brain/brain.service): a read-only system, an empty home directory except for its workspace, its channel's keys (read-only), and the claude binary; its own source is in the Nix store, read-only, so it can read how it works. The systemd and D-Bus sockets, the ssh and gpg agents, and X are hidden. The network is not yet confined: it needs its model's API, but today it could also reach the home network.
|
||||||
|
|
||||||
|
|||||||
@@ -4,6 +4,10 @@ Watching TV used to mean turning the dial to 4 (NBC), 5 (CBS), or 9 (ABC). Now o
|
|||||||
|
|
||||||
Part of the agent is a box within reach of the couch: press its button and talk. Its ears and voice, speech recognition and synthesis, run on a computer at home, so recordings of you never leave the house; the language model behind it sees only a transcript.
|
Part of the agent is a box within reach of the couch: press its button and talk. Its ears and voice, speech recognition and synthesis, run on a computer at home, so recordings of you never leave the house; the language model behind it sees only a transcript.
|
||||||
|
|
||||||
|
<a href="https://archive.org/details/dckc-ultimate-diy-tv-remote/PXL_20261127_152455720.jpg">
|
||||||
|
<img src="https://ia601808.us.archive.org/8/items/dckc-ultimate-diy-tv-remote/PXL_20261127_152455720_thumb.jpg" alt="voice kit with IR remote"/>
|
||||||
|
</a>
|
||||||
|
|
||||||
## "Put on the ballgame," says Dad
|
## "Put on the ballgame," says Dad
|
||||||
|
|
||||||
One request from the couch becomes a dozen steps for the agent, with a look at the screen when it needs one:
|
One request from the couch becomes a dozen steps for the agent, with a look at the screen when it needs one:
|
||||||
@@ -23,10 +27,10 @@ The game isn't on 4, 5, or 9. It's on a sports network in the hundreds, behind t
|
|||||||
|
|
||||||
## How it works
|
## 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.
|
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 Linux machine at home that serves as speech server and agent host; the diagram draws those two apart, since they can be.
|
||||||
|
|
||||||
```
|
```
|
||||||
near the couch speech server brain host
|
near the couch speech server agent host
|
||||||
┌───────────────┐ hear ──▶ ┌──────────────┐
|
┌───────────────┐ hear ──▶ ┌──────────────┐
|
||||||
│ the box │ speak ──▶ │ whisper.cpp │
|
│ the box │ speak ──▶ │ whisper.cpp │
|
||||||
│ Pi 3B │ │ piper │
|
│ Pi 3B │ │ piper │
|
||||||
@@ -55,18 +59,9 @@ An agent in the living room should be able to do what it's for, and no more. A c
|
|||||||
|
|
||||||
The parts talk over [Cap'n Web](https://github.com/cloudflare/capnweb); [CONTRIBUTING](CONTRIBUTING.md#capabilities-on-the-wire) says how.
|
The parts talk over [Cap'n Web](https://github.com/cloudflare/capnweb); [CONTRIBUTING](CONTRIBUTING.md#capabilities-on-the-wire) says how.
|
||||||
|
|
||||||
## Parts
|
|
||||||
|
|
||||||
The agent is built from parts you can buy and solder:
|
|
||||||
|
|
||||||
- **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.
|
|
||||||
- **Home server:** any Linux machine with Nix and systemd, for speech and the brain; x86_64 with AVX2 is plenty. whisper.cpp's base.en model transcribes an 11 s clip in about 2 s.
|
|
||||||
|
|
||||||
## Make your own
|
## Make your own
|
||||||
|
|
||||||
You'll need the parts above, a Linux home server with Nix, and an afternoon. You choose a few names: the box's, your home server's, your Wi-Fi network's. Everything else has a default. The [setup guide](docs/setup.md) walks through it.
|
I made mine from a [Raspberry Pi and Voice Kit from a 2017 project](https://www.madmode.com/2017/sel4-rpi). The [setup guide](docs/setup.md) covers the parts I used; other suitable parts might be easier to find now.
|
||||||
|
|
||||||
## License
|
## License
|
||||||
|
|
||||||
|
|||||||
+14
-23
@@ -1,21 +1,20 @@
|
|||||||
# box: the part of the agent within reach of the couch: a Raspberry Pi 3B with the AIY Voice HAT.
|
# 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
|
# 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.
|
# A box's system, and so its image, come from lib.mkBox in your household's own flake: build the
|
||||||
# Build its image, write it to a card, put the Wi-Fi secret on it, boot the Pi:
|
# image there (nix build), and deploy changes from there (nixos-rebuild). Here, the tools that take
|
||||||
# make image FLAKE=... BOX=...
|
# no household details: write the image to a card, put the Wi-Fi secret on it, boot the Pi:
|
||||||
# make card DEV=/dev/sdX # look first
|
# make card DEV=/dev/sdX # look first
|
||||||
# make flash DEV=/dev/sdX CONFIRM=erase # then write
|
# make flash DEV=/dev/sdX IMG=.../sd-image/x.img CONFIRM=erase # then write
|
||||||
# make wifi-secret SSID=...
|
# make wifi-secret SSID=...
|
||||||
# After that, changes go over ssh: make deploy. Then, on the home server, as the brain's user,
|
# Then, on the home server, as the brain's user,
|
||||||
# with speech and the brain installed: make keys.
|
# with speech and the brain installed: make keys.
|
||||||
|
|
||||||
FLAKE = .
|
|
||||||
BOX = box
|
BOX = box
|
||||||
ADMIN = $(USER)
|
ADMIN = $(USER)
|
||||||
HOST = $(BOX).local
|
HOST = $(BOX).local
|
||||||
NIX = nix --option extra-platforms aarch64-linux
|
|
||||||
DEV =
|
DEV =
|
||||||
|
IMG =
|
||||||
SSID =
|
SSID =
|
||||||
MNT = /mnt/pdtv26-card
|
MNT = /mnt/pdtv26-card
|
||||||
TEXT = Hello. Press my button and talk to me.
|
TEXT = Hello. Press my button and talk to me.
|
||||||
@@ -27,9 +26,11 @@ SECS = 6
|
|||||||
BRAIN_KEYS = $(HOME)/.config/pdtv26-brain
|
BRAIN_KEYS = $(HOME)/.config/pdtv26-brain
|
||||||
CAMERA_URL = $(HOME)/.config/pdtv26-camera/rtsp-url
|
CAMERA_URL = $(HOME)/.config/pdtv26-camera/rtsp-url
|
||||||
SPEECH_KEY = /etc/pdtv26-speech/speech-key
|
SPEECH_KEY = /etc/pdtv26-speech/speech-key
|
||||||
|
# The speech server's host, if it's not this one: its key comes over ssh.
|
||||||
|
SPEECH =
|
||||||
ON_BOX = ssh $(ADMIN)@$(HOST)
|
ON_BOX = ssh $(ADMIN)@$(HOST)
|
||||||
|
|
||||||
.PHONY: help test image card flash wifi-secret deploy say volume record keys speech-key ask-key ir-key look-key rtsp-url
|
.PHONY: help test card flash wifi-secret say volume record keys speech-key ask-key ir-key look-key rtsp-url
|
||||||
|
|
||||||
## list targets
|
## list targets
|
||||||
help:
|
help:
|
||||||
@@ -39,31 +40,21 @@ help:
|
|||||||
test:
|
test:
|
||||||
nix build -L --no-link ..#checks.x86_64-linux.box-js ..#checks.x86_64-linux.box-py ..#checks.x86_64-linux.box-system
|
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
|
## show the card at DEV, and check it's removable, on USB, and under 128 GB
|
||||||
card:
|
card:
|
||||||
./card-check.sh $(DEV)
|
./card-check.sh $(DEV)
|
||||||
|
|
||||||
## erase the card at DEV and write the image: make flash DEV=/dev/sdX CONFIRM=erase
|
## erase the card at DEV and write the image IMG to it: make flash DEV=/dev/sdX IMG=... CONFIRM=erase
|
||||||
# Not "flash: image": image links into the Nix store, where every mtime is 1970, so make would always rebuild.
|
|
||||||
flash: card
|
flash: card
|
||||||
@test "$(CONFIRM)" = erase || { echo "this erases $(DEV); add CONFIRM=erase"; exit 1; }
|
@test "$(CONFIRM)" = erase || { echo "this erases $(DEV); add CONFIRM=erase"; exit 1; }
|
||||||
@test -e image || { echo "no image yet: make image"; exit 1; }
|
@test -f "$(IMG)" || { echo "which image? add IMG=.../sd-image/....img, from your household's nix build"; exit 1; }
|
||||||
./flash.sh image/sd-image/*.img $(DEV)
|
./flash.sh '$(IMG)' $(DEV)
|
||||||
|
|
||||||
## put the Wi-Fi network's PSK on the card, from the passphrase in the desktop keyring: make wifi-secret SSID=...
|
## put the Wi-Fi network's PSK on the card, from the passphrase in the desktop keyring: make wifi-secret SSID=...
|
||||||
wifi-secret:
|
wifi-secret:
|
||||||
@test -n "$(SSID)" || { echo "which network? add SSID=..."; exit 1; }
|
@test -n "$(SSID)" || { echo "which network? add SSID=..."; exit 1; }
|
||||||
./wifi-secret.sh '$(SSID)' $(MNT)
|
./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]
|
## speak TEXT through the box's speaker, with espeak-ng: make say [TEXT="..."] [AMP=0..200]
|
||||||
say:
|
say:
|
||||||
printf '%s\n' "$(TEXT)" | ssh $(ADMIN)@$(HOST) 'espeak-ng -a $(AMP) --stdin --stdout | aplay -q -D speaker'
|
printf '%s\n' "$(TEXT)" | ssh $(ADMIN)@$(HOST) 'espeak-ng -a $(AMP) --stdin --stdout | aplay -q -D speaker'
|
||||||
@@ -79,9 +70,9 @@ record:
|
|||||||
## every key, at both ends of its connection, by pipe: never on disk but where it's used
|
## every key, at both ends of its connection, by pipe: never on disk but where it's used
|
||||||
keys: speech-key ask-key ir-key look-key rtsp-url
|
keys: speech-key ask-key ir-key look-key rtsp-url
|
||||||
|
|
||||||
## speech's key, from here to the box's /etc/pdtv26/speech-key (root's alone)
|
## speech's key, from here (or SPEECH) to the box's /etc/pdtv26/speech-key (root's alone)
|
||||||
speech-key:
|
speech-key:
|
||||||
sudo cat $(SPEECH_KEY) | $(ON_BOX) 'sudo install -D -m 600 /dev/stdin /etc/pdtv26/speech-key && sudo wc -c /etc/pdtv26/speech-key'
|
$(if $(SPEECH),ssh $(SPEECH) )sudo cat $(SPEECH_KEY) | $(ON_BOX) 'sudo install -D -m 600 /dev/stdin /etc/pdtv26/speech-key && sudo wc -c /etc/pdtv26/speech-key'
|
||||||
|
|
||||||
## the brain's ask key (made by ../brain if there's none), from here to the box's /etc/pdtv26/ask-key
|
## the brain's ask key (made by ../brain if there's none), from here to the box's /etc/pdtv26/ask-key
|
||||||
ask-key:
|
ask-key:
|
||||||
|
|||||||
+3
-1
@@ -3,6 +3,7 @@
|
|||||||
* @file ask-client: the box's side of a conversation with the brain, through its ask capability.
|
* @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
|
* usage: ask-client.js URL CONVERSATION < question.txt
|
||||||
* prints JSON lines: {"say": "..."} for each thing the brain says meanwhile,
|
* prints JSON lines: {"say": "..."} for each thing the brain says meanwhile,
|
||||||
|
* then, if the brain changed the volume, {"louder": N} (percentage points; negative is softer),
|
||||||
* then {"reply": "...", "end": false}; end is true when the brain ends the conversation.
|
* then {"reply": "...", "end": false}; end is true when the brain ends the conversation.
|
||||||
* usage: ask-client.js URL CONVERSATION end
|
* usage: ask-client.js URL CONVERSATION end
|
||||||
* tells the brain the conversation is over.
|
* tells the brain the conversation is over.
|
||||||
@@ -45,7 +46,8 @@ const main = async ({
|
|||||||
}
|
}
|
||||||
const question = (await text(stdin)).trim();
|
const question = (await text(stdin)).trim();
|
||||||
// Cap'n Web passes the function by reference: the brain calls it back over this session.
|
// Cap'n Web passes the function by reference: the brain calls it back over this session.
|
||||||
const { text: reply, end } = await asker.ask(question, conversation, (/** @type {string} */ said) => { line({ say: said }); });
|
const { text: reply, end, louder } = await asker.ask(question, conversation, (/** @type {string} */ said) => { line({ say: said }); });
|
||||||
|
if (louder) line({ louder });
|
||||||
line({ reply, end });
|
line({ reply, end });
|
||||||
} finally {
|
} finally {
|
||||||
gate[Symbol.dispose]();
|
gate[Symbol.dispose]();
|
||||||
|
|||||||
+15
-7
@@ -13,7 +13,8 @@ While the brain looks through the camera (../look.js), the box taps and flashes
|
|||||||
One event loop, no threads. Only _script_io() imports authority (the DisciplinedPython
|
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:
|
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
|
button and light (gpio.py, button.py, light.py), mics (hearing.py), speaker and voice
|
||||||
(voice.py), hear and brain (brain.py), status (status.py), and the look signal.
|
(voice.py), the volume (mixer.py), muting the TV while it listens (muting.py), hear and
|
||||||
|
brain (brain.py), status (status.py), and the look signal.
|
||||||
"""
|
"""
|
||||||
import asyncio
|
import asyncio
|
||||||
import logging
|
import logging
|
||||||
@@ -27,6 +28,8 @@ from gpio import HatLines
|
|||||||
from hearing import ARECORD_ARGS, Mics
|
from hearing import ARECORD_ARGS, Mics
|
||||||
from light import Light
|
from light import Light
|
||||||
from look_signal import LookSignal
|
from look_signal import LookSignal
|
||||||
|
from mixer import Mixer
|
||||||
|
from muting import Muting
|
||||||
from status import Status, ignore, poster
|
from status import Status, ignore, poster
|
||||||
from voice import Speaker, Voice
|
from voice import Speaker, Voice
|
||||||
|
|
||||||
@@ -45,16 +48,17 @@ def activated_socket(environ, getpid, socket):
|
|||||||
|
|
||||||
|
|
||||||
async def main(argv, environ, getpid, cwd, request_lines, socket, create_subprocess_exec, open_connection,
|
async def main(argv, environ, getpid, cwd, request_lines, socket, create_subprocess_exec, open_connection,
|
||||||
start_unix_server, sleep, monotonic, now):
|
open_unix_connection, start_unix_server, sleep, monotonic, now):
|
||||||
"""box.py APLAY ARECORD ESPEAK HEAR_CLIENT SPEAK_CLIENT SPEECH_URL ASK_CLIENT ASK_URL EARCONS STATE_DIR [STATUS_URL]
|
"""box.py APLAY AMIXER ARECORD ESPEAK HEAR_CLIENT SPEAK_CLIENT SPEECH_URL ASK_CLIENT ASK_URL MUTE_SOCKET EARCONS STATE_DIR [STATUS_URL]
|
||||||
|
|
||||||
HEAR_CLIENT SPEECH_URL < clip prints its transcript; SPEAK_CLIENT SPEECH_URL < text prints
|
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.
|
a WAV of it; ASK_CLIENT ASK_URL CONVERSATION < text prints the brain's answer as JSON lines.
|
||||||
|
MUTE_SOCKET is the ir service's conversation socket, held open for each conversation (muting.py).
|
||||||
EARCONS is a directory of WAVs (voice.EARCONS); STATE_DIR keeps the latest clip.
|
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.
|
STATUS_URL, if any, is a status page, told of each conversation and look, with a heartbeat.
|
||||||
"""
|
"""
|
||||||
(aplay, arecord, espeak, hear_client, speak_client, speech_url, ask_client, ask_url,
|
(aplay, amixer, arecord, espeak, hear_client, speak_client, speech_url, ask_client, ask_url,
|
||||||
earcons, state_dir, *status_url) = argv[1:]
|
mute_socket, earcons, state_dir, *status_url) = argv[1:]
|
||||||
command = partial(Command, create_subprocess_exec)
|
command = partial(Command, create_subprocess_exec)
|
||||||
loop = asyncio.get_running_loop()
|
loop = asyncio.get_running_loop()
|
||||||
|
|
||||||
@@ -63,10 +67,12 @@ async def main(argv, environ, getpid, cwd, request_lines, socket, create_subproc
|
|||||||
loop.add_reader(lines.fileno(), lambda: button.feed(lines.read_edges()))
|
loop.add_reader(lines.fileno(), lambda: button.feed(lines.read_edges()))
|
||||||
light = Light(lines.set_led, monotonic, sleep)
|
light = Light(lines.set_led, monotonic, sleep)
|
||||||
speaker = Speaker(command(aplay, "-q", "-D", "speaker"), cwd / earcons)
|
speaker = Speaker(command(aplay, "-q", "-D", "speaker"), cwd / earcons)
|
||||||
|
mixer = Mixer(command(amixer, "-c", "voicehat"))
|
||||||
mics = Mics(command(arecord, *ARECORD_ARGS), keep=(cwd / state_dir / "clip.wav").write_bytes)
|
mics = Mics(command(arecord, *ARECORD_ARGS), keep=(cwd / state_dir / "clip.wav").write_bytes)
|
||||||
hear = Hear(command(hear_client, speech_url))
|
hear = Hear(command(hear_client, speech_url))
|
||||||
voice = Voice(command(speak_client, speech_url), command(espeak, "--stdout"), speaker, button)
|
voice = Voice(command(speak_client, speech_url), command(espeak, "--stdout"), speaker, button)
|
||||||
brain = Brain(command(ask_client, ask_url), button)
|
brain = Brain(command(ask_client, ask_url), button)
|
||||||
|
muting = Muting(partial(open_unix_connection, mute_socket))
|
||||||
|
|
||||||
background = [asyncio.create_task(light.run())]
|
background = [asyncio.create_task(light.run())]
|
||||||
note = ignore
|
note = ignore
|
||||||
@@ -87,8 +93,9 @@ async def main(argv, environ, getpid, cwd, request_lines, socket, create_subproc
|
|||||||
convo = now().strftime("%Y%m%d-%H%M%S")
|
convo = now().strftime("%Y%m%d-%H%M%S")
|
||||||
logging.info(f"{convo}: a conversation starts")
|
logging.info(f"{convo}: a conversation starts")
|
||||||
note("conversation")
|
note("conversation")
|
||||||
|
async with muting.during():
|
||||||
await converse(convo, partial(mics.listen, button=button), hear.transcribe, brain.ask,
|
await converse(convo, partial(mics.listen, button=button), hear.transcribe, brain.ask,
|
||||||
voice.speak, speaker.play, light.mics, light.thinking, brain.end,
|
voice.speak, speaker.play, mixer.louder, light.mics, light.thinking, brain.end,
|
||||||
logging.info, note)
|
logging.info, note)
|
||||||
button.pressed() # presses during goodbye don't start another
|
button.pressed() # presses during goodbye don't start another
|
||||||
for task in background:
|
for task in background:
|
||||||
@@ -112,7 +119,8 @@ if __name__ == "__main__":
|
|||||||
argv=list(sys.argv), environ=dict(os.environ), getpid=os.getpid, cwd=Path.cwd(),
|
argv=list(sys.argv), environ=dict(os.environ), getpid=os.getpid, cwd=Path.cwd(),
|
||||||
request_lines=gpiod.request_lines, socket=socket.socket,
|
request_lines=gpiod.request_lines, socket=socket.socket,
|
||||||
create_subprocess_exec=asyncio.create_subprocess_exec,
|
create_subprocess_exec=asyncio.create_subprocess_exec,
|
||||||
open_connection=asyncio.open_connection, start_unix_server=asyncio.start_unix_server,
|
open_connection=asyncio.open_connection, open_unix_connection=asyncio.open_unix_connection,
|
||||||
|
start_unix_server=asyncio.start_unix_server,
|
||||||
sleep=asyncio.sleep, monotonic=time.monotonic, now=datetime.now,
|
sleep=asyncio.sleep, monotonic=time.monotonic, now=datetime.now,
|
||||||
))
|
))
|
||||||
|
|
||||||
|
|||||||
+5
-1
@@ -25,17 +25,21 @@ def answer(line):
|
|||||||
|
|
||||||
>>> answer(b'{"say": "Let me try."}')
|
>>> answer(b'{"say": "Let me try."}')
|
||||||
('say', 'Let me try.')
|
('say', 'Let me try.')
|
||||||
|
>>> answer(b'{"louder": -10}')
|
||||||
|
('louder', -10)
|
||||||
>>> answer(b'{"reply": "Bye!", "end": true}')
|
>>> answer(b'{"reply": "Bye!", "end": true}')
|
||||||
('reply', 'Bye!', True)
|
('reply', 'Bye!', True)
|
||||||
"""
|
"""
|
||||||
event = json.loads(line)
|
event = json.loads(line)
|
||||||
if "say" in event:
|
if "say" in event:
|
||||||
return ("say", event["say"])
|
return ("say", event["say"])
|
||||||
|
if "louder" in event:
|
||||||
|
return ("louder", int(event["louder"]))
|
||||||
return ("reply", event["reply"], bool(event.get("end")))
|
return ("reply", event["reply"], bool(event.get("end")))
|
||||||
|
|
||||||
|
|
||||||
class Brain:
|
class Brain:
|
||||||
"""ask(text, convo) yields ("say", text)s, then ("reply", text, end); or ("press",).
|
"""ask(text, convo) yields ("say", text)s, perhaps ("louder", points), then ("reply", text, end); or ("press",).
|
||||||
end(convo) tells the brain the conversation is over.
|
end(convo) tells the brain the conversation is over.
|
||||||
|
|
||||||
ask_client is a Command for ask-client, bound to the brain's ask capability.
|
ask_client is a Command for ask-client, bound to the brain's ask capability.
|
||||||
|
|||||||
+35
-4
@@ -1,17 +1,18 @@
|
|||||||
"""One conversation with the box, from the press that opened it to goodbye.
|
"""One conversation with the box, from the press that opened it to goodbye.
|
||||||
|
|
||||||
Everything it touches comes in as a function: listen, transcribe, ask, speak, play, the LED.
|
Everything it touches comes in as a function: listen, transcribe, ask, speak, play, the volume, the LED.
|
||||||
"""
|
"""
|
||||||
from contextlib import aclosing
|
from contextlib import aclosing
|
||||||
|
|
||||||
|
|
||||||
async def converse(convo, listen, transcribe, ask, speak, play, led, thinking, end, log,
|
async def converse(convo, listen, transcribe, ask, speak, play, louder, led, thinking, end, log,
|
||||||
note=lambda kind, **data: None):
|
note=lambda kind, **data: None):
|
||||||
"""One conversation, from the press that opened it to goodbye.
|
"""One conversation, from the press that opened it to goodbye.
|
||||||
|
|
||||||
Async: listen(skip_s) returns ("speech", clip), ("quiet", None), or ("press", None).
|
Async: listen(skip_s) returns ("speech", clip), ("quiet", None), or ("press", None).
|
||||||
play(name) starts an earcon and returns its length, which listen skips.
|
play(name) starts an earcon and returns its length, which listen skips.
|
||||||
ask(text, convo) yields ("say", text), then ("reply", text, end); or ("press",).
|
ask(text, convo) yields ("say", text), perhaps ("louder", points), then ("reply", text, end); or ("press",).
|
||||||
|
louder(points) changes the speaker volume, before the reply is spoken, and returns the new level.
|
||||||
speak(text) returns False if a press interrupted it. end(convo) tells the brain.
|
speak(text) returns False if a press interrupted it. end(convo) tells the brain.
|
||||||
Not async: led(on), thinking(on), log(msg), and
|
Not async: led(on), thinking(on), log(msg), and
|
||||||
note(kind, ...) counts it for a status page: turn, huh, interrupt, end.
|
note(kind, ...) counts it for a status page: turn, huh, interrupt, end.
|
||||||
@@ -25,6 +26,9 @@ async def converse(convo, listen, transcribe, ask, speak, play, led, thinking, e
|
|||||||
... if text == "Switch to the PC.":
|
... if text == "Switch to the PC.":
|
||||||
... yield ("say", "Let me try.")
|
... yield ("say", "Let me try.")
|
||||||
... yield ("reply", "Done.", False)
|
... yield ("reply", "Done.", False)
|
||||||
|
... elif text == "Speak up!":
|
||||||
|
... yield ("louder", 10)
|
||||||
|
... yield ("reply", "Is this better?", False)
|
||||||
... elif text == "Thanks!":
|
... elif text == "Thanks!":
|
||||||
... yield ("reply", "You're welcome. Bye!", True)
|
... yield ("reply", "You're welcome. Bye!", True)
|
||||||
... else:
|
... else:
|
||||||
@@ -33,7 +37,8 @@ async def converse(convo, listen, transcribe, ask, speak, play, led, thinking, e
|
|||||||
>>> async def speak(text): return print("speak", text) or True
|
>>> async def speak(text): return print("speak", text) or True
|
||||||
>>> async def play(name): return print("play", name) or 0.4
|
>>> async def play(name): return print("play", name) or 0.4
|
||||||
>>> async def end(convo): print("end", convo)
|
>>> async def end(convo): print("end", convo)
|
||||||
>>> ops = dict(transcribe=transcribe, ask=ask, speak=speak, play=play, end=end, log=print,
|
>>> async def louder(points): return 45 + points
|
||||||
|
>>> ops = dict(transcribe=transcribe, ask=ask, speak=speak, play=play, louder=louder, end=end, log=print,
|
||||||
... led=lambda on: print("led", on), thinking=lambda on: print("thinking", on))
|
... led=lambda on: print("led", on), thinking=lambda on: print("thinking", on))
|
||||||
>>> run = lambda convo, listen, **kw: asyncio.run(converse(convo, listen, **kw))
|
>>> run = lambda convo, listen, **kw: asyncio.run(converse(convo, listen, **kw))
|
||||||
>>> run("k1", script(("speech", "Switch to the PC."), ("speech", "Thanks!")), **ops)
|
>>> run("k1", script(("speech", "Switch to the PC."), ("speech", "Thanks!")), **ops)
|
||||||
@@ -62,6 +67,26 @@ async def converse(convo, listen, transcribe, ask, speak, play, led, thinking, e
|
|||||||
play bye
|
play bye
|
||||||
end k1
|
end k1
|
||||||
|
|
||||||
|
The brain can turn the volume up or down; the box does so before it speaks the reply:
|
||||||
|
|
||||||
|
>>> run("k4", script(("speech", "Speak up!"), ("press", None)), **ops)
|
||||||
|
play open
|
||||||
|
led True
|
||||||
|
led False
|
||||||
|
play gotit
|
||||||
|
thinking True
|
||||||
|
k4 heard: Speak up!
|
||||||
|
k4: volume 55%
|
||||||
|
thinking False
|
||||||
|
speak Is this better?
|
||||||
|
thinking False
|
||||||
|
play turn
|
||||||
|
led True
|
||||||
|
led False
|
||||||
|
k4: press; goodbye
|
||||||
|
play bye
|
||||||
|
end k4
|
||||||
|
|
||||||
A press while the agent thinks interrupts it; silence ends the conversation:
|
A press while the agent thinks interrupts it; silence ends the conversation:
|
||||||
|
|
||||||
>>> run("k2", script(("speech", "Tell me a long story."), ("quiet", None)), **ops)
|
>>> run("k2", script(("speech", "Tell me a long story."), ("quiet", None)), **ops)
|
||||||
@@ -143,6 +168,12 @@ async def converse(convo, listen, transcribe, ask, speak, play, led, thinking, e
|
|||||||
try:
|
try:
|
||||||
async with aclosing(ask(text, convo)) as events: # a break closes it now, not someday
|
async with aclosing(ask(text, convo)) as events: # a break closes it now, not someday
|
||||||
async for event in events:
|
async for event in events:
|
||||||
|
if event[0] == "louder":
|
||||||
|
try:
|
||||||
|
log(f"{convo}: volume {await louder(event[1])}%")
|
||||||
|
except Exception as err:
|
||||||
|
log(f"{convo}: volume change failed: {err}")
|
||||||
|
continue
|
||||||
thinking(False)
|
thinking(False)
|
||||||
if event[0] == "press" or not await speak(event[1]):
|
if event[0] == "press" or not await speak(event[1]):
|
||||||
interrupted = True
|
interrupted = True
|
||||||
|
|||||||
@@ -0,0 +1,56 @@
|
|||||||
|
"""The box's speaker volume: the softvol named speaker (../voicehat.nix), which the brain may nudge.
|
||||||
|
|
||||||
|
The brain asks for louder or softer, in percentage points, with a reply; the box keeps the level
|
||||||
|
within its own bounds, so no reply can make it silent or painfully loud.
|
||||||
|
"""
|
||||||
|
import re
|
||||||
|
|
||||||
|
LOWEST, HIGHEST = 10, 80 # percent; full volume is too loud for a living room
|
||||||
|
|
||||||
|
|
||||||
|
def percent(amixer_out):
|
||||||
|
"""The level amixer sget reports, in percent.
|
||||||
|
|
||||||
|
>>> percent(b"Simple mixer control 'speaker',0\\n Front Left: 115 [45%]\\n Front Right: 115 [45%]\\n")
|
||||||
|
45
|
||||||
|
"""
|
||||||
|
found = re.search(rb"\[(\d+)%\]", amixer_out)
|
||||||
|
if not found:
|
||||||
|
raise IOError(f"no level in amixer's output: {amixer_out[:200]!r}")
|
||||||
|
return int(found.group(1))
|
||||||
|
|
||||||
|
|
||||||
|
def nudge(level, louder, lowest=LOWEST, highest=HIGHEST):
|
||||||
|
"""level, louder by so many points, within bounds.
|
||||||
|
|
||||||
|
>>> nudge(45, 10), nudge(45, -10), nudge(75, 30), nudge(15, -30)
|
||||||
|
(55, 35, 80, 10)
|
||||||
|
"""
|
||||||
|
return max(lowest, min(highest, level + louder))
|
||||||
|
|
||||||
|
|
||||||
|
class Mixer:
|
||||||
|
"""louder(points) changes the speaker's level and returns the new one, in percent.
|
||||||
|
|
||||||
|
amixer is a Command for amixer on the box's sound card (amixer -c voicehat).
|
||||||
|
|
||||||
|
>>> import asyncio
|
||||||
|
>>> class Amixer:
|
||||||
|
... level = 45
|
||||||
|
... async def run(self, *args):
|
||||||
|
... print(args)
|
||||||
|
... if args[-1].endswith("%"): self.level = int(args[-1][:-1])
|
||||||
|
... return f" Front Left: 0 [{self.level}%]".encode()
|
||||||
|
>>> asyncio.run(Mixer(Amixer()).louder(50))
|
||||||
|
('sget', 'speaker')
|
||||||
|
('-q', 'sset', 'speaker', '80%')
|
||||||
|
80
|
||||||
|
"""
|
||||||
|
|
||||||
|
def __init__(self, amixer):
|
||||||
|
self.__amixer = amixer
|
||||||
|
|
||||||
|
async def louder(self, points):
|
||||||
|
level = nudge(percent(await self.__amixer.run("sget", "speaker")), int(points))
|
||||||
|
await self.__amixer.run("-q", "sset", "speaker", f"{level}%")
|
||||||
|
return level
|
||||||
@@ -0,0 +1,56 @@
|
|||||||
|
"""Muting the TV while the box listens: the button service's side.
|
||||||
|
|
||||||
|
For the whole of a conversation, the button service holds a connection to the ir service's
|
||||||
|
conversation socket (../ir-server.js); if the brain has turned muting on, the ir service mutes
|
||||||
|
the TV when the connection opens and unmutes it when it closes. This side can't send any code,
|
||||||
|
nor tell whether muting is on: the connection says only that a conversation is going on.
|
||||||
|
"""
|
||||||
|
import logging
|
||||||
|
from contextlib import asynccontextmanager
|
||||||
|
|
||||||
|
|
||||||
|
class Muting:
|
||||||
|
"""during(): for the length of a conversation, the ir service may mute the TV.
|
||||||
|
|
||||||
|
open_unix_connection is asyncio's, bound to the ir service's conversation socket; log, logging.info.
|
||||||
|
|
||||||
|
>>> import asyncio
|
||||||
|
>>> class Writer:
|
||||||
|
... def close(self): print("hang up")
|
||||||
|
... async def wait_closed(self): pass
|
||||||
|
>>> async def connect(): return print("connect") or (None, Writer())
|
||||||
|
>>> async def talk(muting):
|
||||||
|
... async with muting.during():
|
||||||
|
... print("conversation")
|
||||||
|
>>> asyncio.run(talk(Muting(connect)))
|
||||||
|
connect
|
||||||
|
conversation
|
||||||
|
hang up
|
||||||
|
|
||||||
|
Without the ir service, the conversation goes on, unmuted:
|
||||||
|
|
||||||
|
>>> async def refused(): raise ConnectionRefusedError("no ir service")
|
||||||
|
>>> asyncio.run(talk(Muting(refused, log=print)))
|
||||||
|
mute: can't reach the ir service: no ir service
|
||||||
|
conversation
|
||||||
|
"""
|
||||||
|
|
||||||
|
def __init__(self, open_unix_connection, log=logging.info):
|
||||||
|
self.__connect, self.__log = open_unix_connection, log
|
||||||
|
|
||||||
|
@asynccontextmanager
|
||||||
|
async def during(self):
|
||||||
|
writer = None
|
||||||
|
try:
|
||||||
|
_, writer = await self.__connect()
|
||||||
|
except OSError as err:
|
||||||
|
self.__log(f"mute: can't reach the ir service: {err}")
|
||||||
|
try:
|
||||||
|
yield
|
||||||
|
finally:
|
||||||
|
if writer:
|
||||||
|
try:
|
||||||
|
writer.close()
|
||||||
|
await writer.wait_closed()
|
||||||
|
except OSError as err:
|
||||||
|
self.__log(f"mute: hanging up: {err}")
|
||||||
+45
-4
@@ -5,14 +5,19 @@
|
|||||||
* PICO VERB ARGS... talks to the Pico: listen SECONDS, repeat N GAP_MS CODE... (../ir-pico/pico_tty.py, its tty bound in).
|
* 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.
|
* 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.
|
* The key is in $CREDENTIALS_DIRECTORY/ir-key (systemd LoadCredential), not argv, where ps would show it.
|
||||||
|
*
|
||||||
|
* Muting while the box listens: the button service connects to the socket systemd passes (fd 3) when a
|
||||||
|
* conversation starts, and hangs up when it ends; if the brain turned muting on, the TV is muted
|
||||||
|
* meanwhile. The setting is kept in $STATE_DIRECTORY/mute.json. The button can't send any other code.
|
||||||
*/
|
*/
|
||||||
import { newWebSocketRpcSession } from 'capnweb';
|
import { newWebSocketRpcSession } from 'capnweb';
|
||||||
import { spawn as spawnChild } from 'node:child_process';
|
import { spawn as spawnChild } from 'node:child_process';
|
||||||
import { readFile } from 'node:fs/promises';
|
import { readFile, writeFile } from 'node:fs/promises';
|
||||||
|
import { createServer } from 'node:net';
|
||||||
import process from 'node:process';
|
import process from 'node:process';
|
||||||
import { WebSocketServer } from 'ws';
|
import { WebSocketServer } from 'ws';
|
||||||
import { Gate } from './gate.js';
|
import { Gate } from './gate.js';
|
||||||
import { Ir } from './ir.js';
|
import { Ir, Muting } from './ir.js';
|
||||||
import { makeCommand, timed } from './run.js';
|
import { makeCommand, timed } from './run.js';
|
||||||
|
|
||||||
/** The lines worth logging of what the Pico printed. */
|
/** The lines worth logging of what the Pico printed. */
|
||||||
@@ -24,7 +29,10 @@ const PICO_SAID = /^(got|sent|unparsed|bad)/;
|
|||||||
* @param {object} [io] what it reaches; the process's own, by default
|
* @param {object} [io] what it reaches; the process's own, by default
|
||||||
* @param {string[]} [io.argv] HOST PORT PICO [STATUS_URL]
|
* @param {string[]} [io.argv] HOST PORT PICO [STATUS_URL]
|
||||||
* @param {Record<string, string | undefined>} [io.env] for CREDENTIALS_DIRECTORY
|
* @param {Record<string, string | undefined>} [io.env] for CREDENTIALS_DIRECTORY
|
||||||
* @param {typeof readFile} [io.read] reads the key
|
* @param {typeof readFile} [io.read] reads the key and the mute setting
|
||||||
|
* @param {typeof writeFile} [io.write] keeps the mute setting
|
||||||
|
* @param {typeof createServer} [io.serveLocal] serves the conversation socket, from systemd
|
||||||
|
* @param {() => number} [io.pid] to check the socket is for us
|
||||||
* @param {typeof spawnChild} [io.spawn] runs PICO, and nothing else
|
* @param {typeof spawnChild} [io.spawn] runs PICO, and nothing else
|
||||||
* @param {typeof fetch} [io.post] reaches STATUS_URL, and nothing else
|
* @param {typeof fetch} [io.post] reaches STATUS_URL, and nothing else
|
||||||
* @param {() => number} [io.now] the clock, for timing jobs
|
* @param {() => number} [io.now] the clock, for timing jobs
|
||||||
@@ -35,6 +43,9 @@ const main = async ({
|
|||||||
argv = process.argv.slice(2),
|
argv = process.argv.slice(2),
|
||||||
env = process.env,
|
env = process.env,
|
||||||
read = readFile,
|
read = readFile,
|
||||||
|
write = writeFile,
|
||||||
|
serveLocal = createServer,
|
||||||
|
pid = () => process.pid,
|
||||||
spawn = spawnChild,
|
spawn = spawnChild,
|
||||||
post = fetch,
|
post = fetch,
|
||||||
now = Date.now,
|
now = Date.now,
|
||||||
@@ -53,14 +64,44 @@ const main = async ({
|
|||||||
method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ source: 'pdtv26-ir', ...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}`));
|
}).then((res) => { if (!res.ok) console.error(`status: ${res.status}`); }, (err) => console.error(`status: ${err.message}`));
|
||||||
};
|
};
|
||||||
|
const muteFile = env.STATE_DIRECTORY ? `${env.STATE_DIRECTORY}/mute.json` : undefined;
|
||||||
|
const saved = muteFile ? await read(muteFile, 'utf8').then(JSON.parse, (err) => {
|
||||||
|
if (err.code !== 'ENOENT') console.error(`mute setting unreadable, so off: ${err.message}`);
|
||||||
|
return undefined;
|
||||||
|
}) : undefined;
|
||||||
|
const muting = new Muting(saved, async (codes) => {
|
||||||
|
if (!muteFile) throw new Error('no STATE_DIRECTORY to keep the mute setting in');
|
||||||
|
await write(muteFile, `${JSON.stringify(codes ?? {})}\n`);
|
||||||
|
console.log(`mute while listening: ${codes ? JSON.stringify(codes) : 'off'}`);
|
||||||
|
});
|
||||||
const ir = new Ir(async (args) => {
|
const ir = new Ir(async (args) => {
|
||||||
const out = await timed(now, `pico ${args.join(' ')}`,
|
const out = await timed(now, `pico ${args.join(' ')}`,
|
||||||
async () => (await makeCommand(spawn, pico, args)('')).toString(),
|
async () => (await makeCommand(spawn, pico, args)('')).toString(),
|
||||||
(o) => o.trim().split('\n').filter((ln) => PICO_SAID.test(ln)).join('; ') || '(nothing)');
|
(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]) });
|
if (args[0] === 'repeat') report({ kind: 'ir', code: args.slice(3).join(' '), times: Number(args[1]) });
|
||||||
return out;
|
return out;
|
||||||
});
|
}, muting);
|
||||||
const gate = new Gate(key, ir);
|
const gate = new Gate(key, ir);
|
||||||
|
|
||||||
|
if (env.LISTEN_FDS === '1' && env.LISTEN_PID === String(pid())) {
|
||||||
|
/** @param {string} code */
|
||||||
|
const send = (code) => ir.send(code);
|
||||||
|
serveLocal((conn) => {
|
||||||
|
const ending = muting.start(send);
|
||||||
|
ending.then(() => muting.codes && console.log('a conversation: muted'),
|
||||||
|
(err) => console.error(`a conversation: mute failed: ${err.message}`));
|
||||||
|
conn.on('error', (err) => console.error(`conversation socket: ${err.message}`));
|
||||||
|
conn.on('close', () => {
|
||||||
|
ending.then(
|
||||||
|
(unmute) => unmute().then((outcome) => console.log(`the conversation ended: ${outcome}`),
|
||||||
|
(err) => console.error(`the conversation ended: unmute failed: ${err.message}`)),
|
||||||
|
() => console.error('the conversation ended; muting had failed, so no unmute'));
|
||||||
|
});
|
||||||
|
conn.resume(); // nothing to read; just notice the hang-up
|
||||||
|
}).listen({ fd: 3 });
|
||||||
|
} else {
|
||||||
|
console.log('no conversation socket from systemd: muting while listening is off');
|
||||||
|
}
|
||||||
const wss = listen({ host, port: Number(port), maxPayload: 64 * 1024 });
|
const wss = listen({ host, port: Number(port), maxPayload: 64 * 1024 });
|
||||||
wss.on('connection', (ws, req) => {
|
wss.on('connection', (ws, req) => {
|
||||||
console.log(`connection from ${req.socket.remoteAddress}`);
|
console.log(`connection from ${req.socket.remoteAddress}`);
|
||||||
|
|||||||
@@ -64,6 +64,75 @@ export const parseHeard = (out) => {
|
|||||||
return { codes, unparsed: lines.filter((ln) => ln.startsWith('unparsed:')) };
|
return { codes, unparsed: lines.filter((ln) => ln.startsWith('unparsed:')) };
|
||||||
};
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* A code as send takes it, normalized; or a TypeError.
|
||||||
|
* @param {unknown} code
|
||||||
|
*/
|
||||||
|
export const checkCode = (code) => {
|
||||||
|
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`);
|
||||||
|
}
|
||||||
|
return norm;
|
||||||
|
};
|
||||||
|
|
||||||
|
/** @typedef {{ mute: string, unmute: string }} MuteCodes */
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Whether to mute the TV while the box listens: a setting, and nothing sensed. Mute is often a toggle,
|
||||||
|
* and a camera can't reliably tell whether the TV is muted, so whoever holds the ir capability
|
||||||
|
* turns this on or off, and the box doesn't guess.
|
||||||
|
*/
|
||||||
|
export class Muting {
|
||||||
|
/** @type {MuteCodes | undefined} */
|
||||||
|
#codes;
|
||||||
|
#save;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param {unknown} saved what save was last given, if anything
|
||||||
|
* @param {(codes: MuteCodes | undefined) => Promise<void>} save keeps the setting across restarts
|
||||||
|
*/
|
||||||
|
constructor(saved, save) {
|
||||||
|
const s = /** @type {any} */ (saved);
|
||||||
|
this.#codes = s?.mute ? { mute: checkCode(s.mute), unmute: checkCode(s.unmute ?? s.mute) } : undefined;
|
||||||
|
this.#save = save;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Turn it on, with the code that mutes (and the one that unmutes, if not the same); or off, with no code.
|
||||||
|
* @param {string} [code] @param {string} [unmuteCode]
|
||||||
|
*/
|
||||||
|
async set(code, unmuteCode) {
|
||||||
|
if (!code) {
|
||||||
|
this.#codes = undefined;
|
||||||
|
await this.#save(undefined);
|
||||||
|
return 'off: the box no longer mutes anything while it listens';
|
||||||
|
}
|
||||||
|
const codes = { mute: checkCode(code), unmute: unmuteCode ? checkCode(unmuteCode) : checkCode(code) };
|
||||||
|
this.#codes = codes;
|
||||||
|
await this.#save(codes);
|
||||||
|
return codes.mute === codes.unmute
|
||||||
|
? `on: the box sends ${codes.mute} when a conversation starts, and again when it ends`
|
||||||
|
: `on: the box sends ${codes.mute} when a conversation starts, and ${codes.unmute} when it ends`;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** @returns {MuteCodes | undefined} */
|
||||||
|
get codes() { return this.#codes; }
|
||||||
|
|
||||||
|
/**
|
||||||
|
* A conversation starts: mute, if the setting is on. Resolves to what unmutes at its end, with the
|
||||||
|
* codes it muted with, even if the setting changes meanwhile.
|
||||||
|
* @param {(code: string) => Promise<string>} send
|
||||||
|
* @returns {Promise<() => Promise<string>>}
|
||||||
|
*/
|
||||||
|
async start(send) {
|
||||||
|
const codes = this.#codes;
|
||||||
|
if (!codes) return async () => 'muting is off';
|
||||||
|
await send(codes.mute);
|
||||||
|
return () => send(codes.unmute);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* listen(seconds) reports the codes a remote sent meanwhile; send(code, times, gapMs) sends one,
|
* 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.
|
* times times, gapMs apart: quick enough that a TV's input menu stays open between presses.
|
||||||
@@ -74,10 +143,25 @@ export class Ir extends RpcTarget {
|
|||||||
/** @type {Promise<unknown>} the job before this one */
|
/** @type {Promise<unknown>} the job before this one */
|
||||||
#last = Promise.resolve();
|
#last = Promise.resolve();
|
||||||
|
|
||||||
/** @param {(args: string[]) => Promise<string>} pico runs pico_tty.py's verbs: listen SECONDS, repeat N GAP_MS CODE... */
|
#muting;
|
||||||
constructor(pico) {
|
|
||||||
|
/**
|
||||||
|
* @param {(args: string[]) => Promise<string>} pico runs pico_tty.py's verbs: listen SECONDS, repeat N GAP_MS CODE...
|
||||||
|
* @param {Muting} [muting] whether to mute the TV while the box listens
|
||||||
|
*/
|
||||||
|
constructor(pico, muting = undefined) {
|
||||||
super();
|
super();
|
||||||
this.#pico = pico;
|
this.#pico = pico;
|
||||||
|
this.#muting = muting;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Mute the TV while the box listens, with these codes; or, with no code, don't.
|
||||||
|
* @param {string} [code] @param {string} [unmuteCode] if not the same: mute is often a toggle
|
||||||
|
*/
|
||||||
|
muteWhileListening(code, unmuteCode) {
|
||||||
|
if (!this.#muting) throw new Error('this box has no mute setting');
|
||||||
|
return this.#muting.set(code, unmuteCode);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -106,10 +190,7 @@ export class Ir extends RpcTarget {
|
|||||||
* @param {number} [gapMs] between presses, 100 to 2000
|
* @param {number} [gapMs] between presses, 100 to 2000
|
||||||
*/
|
*/
|
||||||
send(code, times = 1, gapMs = 400) {
|
send(code, times = 1, gapMs = 400) {
|
||||||
const norm = typeof code === 'string' ? normalize(code) : '';
|
const norm = checkCode(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) {
|
if (!Number.isInteger(times) || times < 1 || times > MAX_TIMES) {
|
||||||
throw new RangeError(`times: a whole number, 1 to ${MAX_TIMES}`);
|
throw new RangeError(`times: a whole number, 1 to ${MAX_TIMES}`);
|
||||||
}
|
}
|
||||||
|
|||||||
+36
-1
@@ -1,7 +1,7 @@
|
|||||||
// Tests for the ir capability, with a fake Pico: no serial port.
|
// Tests for the ir capability, with a fake Pico: no serial port.
|
||||||
import { test } from 'node:test';
|
import { test } from 'node:test';
|
||||||
import assert from 'node:assert/strict';
|
import assert from 'node:assert/strict';
|
||||||
import { Ir, parseHeard } from './ir.js';
|
import { Ir, Muting, parseHeard } from './ir.js';
|
||||||
|
|
||||||
test('listen sorts decoded codes from unparsed bursts', async () => {
|
test('listen sorts decoded codes from unparsed bursts', async () => {
|
||||||
const calls = [];
|
const calls = [];
|
||||||
@@ -99,3 +99,38 @@ test('one at a time: a send waits for a listen to finish', async () => {
|
|||||||
test('parseHeard of nothing', () => {
|
test('parseHeard of nothing', () => {
|
||||||
assert.deepEqual(parseHeard(''), { codes: [], unparsed: [] });
|
assert.deepEqual(parseHeard(''), { codes: [], unparsed: [] });
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test('muting while listening: off until the brain sets it; a toggle sends one code twice', async () => {
|
||||||
|
const saves = [];
|
||||||
|
const sent = [];
|
||||||
|
const send = async (code) => { sent.push(code); return `sent ${code}`; };
|
||||||
|
const muting = new Muting(undefined, async (codes) => { saves.push(codes); });
|
||||||
|
const ir = new Ir(async () => '', muting);
|
||||||
|
assert.equal(await (await muting.start(send))(), 'muting is off');
|
||||||
|
assert.deepEqual(sent, []);
|
||||||
|
|
||||||
|
assert.match(await ir.muteWhileListening('raw 2390 620 590'), /again when it ends/);
|
||||||
|
assert.deepEqual(saves, [{ mute: 'raw 2390 620 590', unmute: 'raw 2390 620 590' }]);
|
||||||
|
const unmute = await muting.start(send);
|
||||||
|
assert.deepEqual(sent, ['raw 2390 620 590']);
|
||||||
|
await unmute();
|
||||||
|
assert.deepEqual(sent, ['raw 2390 620 590', 'raw 2390 620 590']);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('muting with separate codes unmutes with the codes it muted with, even if the setting changes meanwhile', async () => {
|
||||||
|
const sent = [];
|
||||||
|
const send = async (code) => { sent.push(code); return `sent ${code}`; };
|
||||||
|
const muting = new Muting({ mute: 'samsung e0 e0 f0 0f', unmute: '20 DF 90 6F' }, async () => {});
|
||||||
|
const unmute = await muting.start(send);
|
||||||
|
assert.match(await muting.set(), /^off/);
|
||||||
|
await unmute();
|
||||||
|
assert.deepEqual(sent, ['samsung E0 E0 F0 0F', '20 DF 90 6F']);
|
||||||
|
assert.equal(muting.codes, undefined);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('muting refuses a bad code, keeps the old setting, and a box without it says so', async () => {
|
||||||
|
const muting = new Muting({ mute: '20 DF 90 6F' }, async () => {});
|
||||||
|
await assert.rejects(async () => muting.set('mute please'), /code:/);
|
||||||
|
assert.deepEqual(muting.codes, { mute: '20 DF 90 6F', unmute: '20 DF 90 6F' });
|
||||||
|
assert.throws(() => new Ir(async () => '').muteWhileListening('20 DF 90 6F'), /no mute setting/);
|
||||||
|
});
|
||||||
+16
-2
@@ -114,10 +114,10 @@ in
|
|||||||
# -E -s, not -I: box.py imports its siblings in body/, from the store.
|
# -E -s, not -I: box.py imports its siblings in body/, from the store.
|
||||||
ExecStart = lib.escapeShellArgs [
|
ExecStart = lib.escapeShellArgs [
|
||||||
"${pkgs.python3.withPackages (ps: [ ps.libgpiod ])}/bin/python3" "-E" "-s" "${./body}/box.py"
|
"${pkgs.python3.withPackages (ps: [ ps.libgpiod ])}/bin/python3" "-E" "-s" "${./body}/box.py"
|
||||||
"${pkgs.alsa-utils}/bin/aplay" "${pkgs.alsa-utils}/bin/arecord" "${pkgs.espeak-ng}/bin/espeak-ng"
|
"${pkgs.alsa-utils}/bin/aplay" "${pkgs.alsa-utils}/bin/amixer" "${pkgs.alsa-utils}/bin/arecord" "${pkgs.espeak-ng}/bin/espeak-ng"
|
||||||
(script "hear-client" "${speechJs}/hear-client.js") (script "speak-client" "${speechJs}/speak-client.js")
|
(script "hear-client" "${speechJs}/hear-client.js") (script "speak-client" "${speechJs}/speak-client.js")
|
||||||
cfg.speechUrl
|
cfg.speechUrl
|
||||||
(script "ask-client" "${boxJs}/ask-client.js") cfg.askUrl
|
(script "ask-client" "${boxJs}/ask-client.js") cfg.askUrl "/run/pdtv26-ir-conversation.sock"
|
||||||
cfg.packages.earcons "/var/lib/pdtv26-button"
|
cfg.packages.earcons "/var/lib/pdtv26-button"
|
||||||
] + lib.optionalString (cfg.statusUrl != null) " ${lib.escapeShellArg cfg.statusUrl}";
|
] + lib.optionalString (cfg.statusUrl != null) " ${lib.escapeShellArg cfg.statusUrl}";
|
||||||
# The private network alone: enough to reach speech and the brain, and nothing else.
|
# The private network alone: enough to reach speech and the brain, and nothing else.
|
||||||
@@ -131,11 +131,25 @@ in
|
|||||||
# DeviceAllow's char-ttyACM is looked up in /proc/devices when the service starts; without cdc_acm loaded
|
# 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.
|
# by then (it loads when the Pico enumerates, maybe after boot starts the service), the tty gets EPERM.
|
||||||
boot.kernelModules = [ "cdc_acm" ];
|
boot.kernelModules = [ "cdc_acm" ];
|
||||||
|
# The button service holds a connection here for each conversation, so ir-server can mute the TV
|
||||||
|
# meanwhile, if the brain turned that on. Its group is the whole of who may: the button service.
|
||||||
|
systemd.sockets.pdtv26-ir = {
|
||||||
|
wantedBy = [ "sockets.target" ];
|
||||||
|
socketConfig = {
|
||||||
|
ListenStream = "/run/pdtv26-ir-conversation.sock";
|
||||||
|
SocketGroup = "button";
|
||||||
|
SocketMode = "0660";
|
||||||
|
};
|
||||||
|
};
|
||||||
systemd.services.pdtv26-ir = {
|
systemd.services.pdtv26-ir = {
|
||||||
description = "the box's IR remote, as a capability";
|
description = "the box's IR remote, as a capability";
|
||||||
wantedBy = [ "multi-user.target" ];
|
wantedBy = [ "multi-user.target" ];
|
||||||
|
requires = [ "pdtv26-ir.socket" ];
|
||||||
|
after = [ "pdtv26-ir.socket" ];
|
||||||
serviceConfig = confined // {
|
serviceConfig = confined // {
|
||||||
DynamicUser = true;
|
DynamicUser = true;
|
||||||
|
# mute.json: whether to mute the TV while the box listens, as the brain last set it.
|
||||||
|
StateDirectory = "pdtv26-ir";
|
||||||
SupplementaryGroups = [ "dialout" ];
|
SupplementaryGroups = [ "dialout" ];
|
||||||
LoadCredential = [ "ir-key:${keys}/ir-key" ];
|
LoadCredential = [ "ir-key:${keys}/ir-key" ];
|
||||||
ExecStart =
|
ExecStart =
|
||||||
|
|||||||
+1
-1
@@ -1,6 +1,6 @@
|
|||||||
# A box's whole system, from a few names: what lib.mkBox adds to the box's services.
|
# A box's whole system, from a few names: what lib.mkBox adds to the box's services.
|
||||||
# name the box's host name
|
# name the box's host name
|
||||||
# server the home server's name, where speech and the brain listen
|
# server the speech server and agent host's name: speech and the brain listen there
|
||||||
# wifi the Wi-Fi network the box joins; its PSK goes on the card after imaging (make wifi-secret)
|
# 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
|
# admin who looks after the box, and logs in with sshKeys to deploy
|
||||||
{ name, server, wifi, admin, sshKeys }:
|
{ name, server, wifi, admin, sshKeys }:
|
||||||
|
|||||||
+2
-1
@@ -61,7 +61,8 @@
|
|||||||
}];
|
}];
|
||||||
|
|
||||||
# The amp has no volume control of its own, so a softvol named speaker goes in front of it; everything
|
# The amp has no volume control of its own, so a softvol named speaker goes in front of it; everything
|
||||||
# plays through it. make volume VOL=30% sets the level; persistence keeps it across reboots.
|
# plays through it. make volume VOL=30% sets the level, and the brain can nudge it (body/mixer.py);
|
||||||
|
# persistence keeps it across reboots.
|
||||||
hardware.alsa = {
|
hardware.alsa = {
|
||||||
enable = true;
|
enable = true;
|
||||||
enablePersistence = true;
|
enablePersistence = true;
|
||||||
|
|||||||
+1
-1
@@ -50,7 +50,7 @@ $(WORK)/.mcp.json: Makefile
|
|||||||
# Pre-approve the project's one MCP server and its tools; the trust and dev-channel prompts still want a person.
|
# Pre-approve the project's one MCP server and its tools; the trust and dev-channel prompts still want a person.
|
||||||
$(WORK)/.claude/settings.local.json: Makefile
|
$(WORK)/.claude/settings.local.json: Makefile
|
||||||
install -d $(dir $@)
|
install -d $(dir $@)
|
||||||
echo '{"enabledMcpjsonServers":["box"],"permissions":{"allow":["mcp__box__reply","mcp__box__say","mcp__box__ir_listen","mcp__box__ir_send","mcp__box__report_problem","mcp__box__look","Bash(python3 -I *)"]}}' > $@
|
echo '{"enabledMcpjsonServers":["box"],"permissions":{"allow":["mcp__box__reply","mcp__box__say","mcp__box__ir_listen","mcp__box__ir_send","mcp__box__mute_while_listening","mcp__box__report_problem","mcp__box__look","Bash(python3 -I *)"]}}' > $@
|
||||||
|
|
||||||
## the box's key to ask: 160 random bits; the box needs a copy, in /etc/pdtv26/ask-key
|
## the box's key to ask: 160 random bits; the box needs a copy, in /etc/pdtv26/ask-key
|
||||||
$(CONF)/ask-key:
|
$(CONF)/ask-key:
|
||||||
|
|||||||
+11
-4
@@ -10,11 +10,14 @@ import { RpcTarget } from 'capnweb';
|
|||||||
/** Spoken questions are short. */
|
/** Spoken questions are short. */
|
||||||
export const MAX_QUESTION_CHARS = 2000;
|
export const MAX_QUESTION_CHARS = 2000;
|
||||||
|
|
||||||
|
/** The most a reply can change the box's speaker volume, in percentage points; the box keeps its own bounds. */
|
||||||
|
export const MAX_LOUDER = 30;
|
||||||
|
|
||||||
/** A conversation id: the box makes them up, so keep them tame. */
|
/** A conversation id: the box makes them up, so keep them tame. */
|
||||||
const CONVERSATION = /^[A-Za-z0-9-]{1,40}$/;
|
const CONVERSATION = /^[A-Za-z0-9-]{1,40}$/;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @typedef {{ text: string, end: boolean }} Answer
|
* @typedef {{ text: string, end: boolean, louder?: number }} Answer
|
||||||
* @typedef {{ conversation?: string, onSay?: (text: string) => unknown }} AskOpts
|
* @typedef {{ conversation?: string, onSay?: (text: string) => unknown }} AskOpts
|
||||||
* @typedef {{ resolve: (a: Answer) => void, reject: (e: Error) => void, onSay?: AskOpts['onSay'] }} Pending
|
* @typedef {{ resolve: (a: Answer) => void, reject: (e: Error) => void, onSay?: AskOpts['onSay'] }} Pending
|
||||||
*/
|
*/
|
||||||
@@ -74,13 +77,17 @@ export class Channel {
|
|||||||
/**
|
/**
|
||||||
* The brain's reply tool. Returns what to tell the brain.
|
* The brain's reply tool. Returns what to tell the brain.
|
||||||
* @param {string} chat_id @param {string} text @param {boolean} [end] the conversation is over
|
* @param {string} chat_id @param {string} text @param {boolean} [end] the conversation is over
|
||||||
|
* @param {number} [louder] change the speaker volume this many percentage points first; negative is softer
|
||||||
*/
|
*/
|
||||||
reply(chat_id, text, end = false) {
|
reply(chat_id, text, end = false, louder = undefined) {
|
||||||
const p = this.#pending.get(chat_id);
|
const p = this.#pending.get(chat_id);
|
||||||
if (!p) return `no one is waiting on chat_id ${chat_id}: it timed out or was already answered`;
|
if (!p) return `no one is waiting on chat_id ${chat_id}: it timed out or was already answered`;
|
||||||
|
const volumeOk = louder === undefined || (Number.isInteger(louder) && Math.abs(louder) <= MAX_LOUDER);
|
||||||
this.#pending.delete(chat_id);
|
this.#pending.delete(chat_id);
|
||||||
p.resolve({ text: String(text), end: end === true });
|
p.resolve({ text: String(text), end: end === true, ...(volumeOk && louder ? { louder } : {}) });
|
||||||
return end === true ? 'spoken; the conversation is over' : 'spoken';
|
const outcome = end === true ? 'spoken; the conversation is over' : 'spoken';
|
||||||
|
if (!volumeOk) return `${outcome}, but the volume is unchanged: louder must be a whole number from -${MAX_LOUDER} to ${MAX_LOUDER}`;
|
||||||
|
return louder ? `${outcome}, ${louder > 0 ? 'louder' : 'softer'} by ${Math.abs(louder)} points (within the box's bounds)` : outcome;
|
||||||
}
|
}
|
||||||
|
|
||||||
/** The box says a conversation is over: by goodbye, silence, or a press. @param {string} conversation @param {string} user */
|
/** The box says a conversation is over: by goodbye, silence, or a press. @param {string} conversation @param {string} user */
|
||||||
|
|||||||
+17
-1
@@ -1,7 +1,7 @@
|
|||||||
// Tests for the ask capability's core: no MCP, no network, no real timers.
|
// Tests for the ask capability's core: no MCP, no network, no real timers.
|
||||||
import { test } from 'node:test';
|
import { test } from 'node:test';
|
||||||
import assert from 'node:assert/strict';
|
import assert from 'node:assert/strict';
|
||||||
import { Channel, Asker, MAX_QUESTION_CHARS } from './ask.js';
|
import { Channel, Asker, MAX_LOUDER, MAX_QUESTION_CHARS } from './ask.js';
|
||||||
|
|
||||||
const harness = () => {
|
const harness = () => {
|
||||||
const sent = [], timers = [];
|
const sent = [], timers = [];
|
||||||
@@ -52,6 +52,22 @@ test('the box ends a conversation; the brain hears it, with no question to answe
|
|||||||
assert.throws(() => channel.end('k 7; rm', 'box'), /conversation/);
|
assert.throws(() => channel.end('k 7; rm', 'box'), /conversation/);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test('a reply can turn the volume up or down; out of range, it speaks but leaves the volume', async () => {
|
||||||
|
const { channel } = harness();
|
||||||
|
const up = channel.ask('Speak up!', 'box');
|
||||||
|
assert.match(channel.reply('c1', 'Is this better?', false, 10), /louder by 10/);
|
||||||
|
assert.deepEqual(await up, { text: 'Is this better?', end: false, louder: 10 });
|
||||||
|
const down = channel.ask('Too loud.', 'box');
|
||||||
|
assert.match(channel.reply('c2', 'Sorry.', false, -5), /softer by 5/);
|
||||||
|
assert.deepEqual(await down, { text: 'Sorry.', end: false, louder: -5 });
|
||||||
|
const way = channel.ask('Way up!', 'box');
|
||||||
|
assert.match(channel.reply('c3', 'Okay.', false, MAX_LOUDER + 1), /volume is unchanged/);
|
||||||
|
assert.deepEqual(await way, { text: 'Okay.', end: false });
|
||||||
|
const odd = channel.ask('Louder?', 'box');
|
||||||
|
assert.match(channel.reply('c4', 'Hm.', false, 'max'), /volume is unchanged/);
|
||||||
|
assert.deepEqual(await odd, { text: 'Hm.', end: false });
|
||||||
|
});
|
||||||
|
|
||||||
test('replies go to the right question; a stale chat_id is reported, not thrown', async () => {
|
test('replies go to the right question; a stale chat_id is reported, not thrown', async () => {
|
||||||
const { channel } = harness();
|
const { channel } = harness();
|
||||||
const a = channel.ask('one', 'box');
|
const a = channel.ask('one', 'box');
|
||||||
|
|||||||
+22
-4
@@ -21,7 +21,7 @@ import { networkInterfaces } from 'node:os';
|
|||||||
import process from 'node:process';
|
import process from 'node:process';
|
||||||
import { createInterface } from 'node:readline';
|
import { createInterface } from 'node:readline';
|
||||||
import { WebSocketServer } from 'ws';
|
import { WebSocketServer } from 'ws';
|
||||||
import { Asker, Channel } from './ask.js';
|
import { Asker, Channel, MAX_LOUDER } from './ask.js';
|
||||||
import { Gate } from './gate.js';
|
import { Gate } from './gate.js';
|
||||||
import { makeGitHubPost, makeReporter } from './report.js';
|
import { makeGitHubPost, makeReporter } from './report.js';
|
||||||
|
|
||||||
@@ -36,10 +36,15 @@ const INSTRUCTIONS = [
|
|||||||
|
|
||||||
const REPLY_TOOL = {
|
const REPLY_TOOL = {
|
||||||
name: 'reply',
|
name: 'reply',
|
||||||
description: 'Speak your answer through the box; then it is their turn. Pass chat_id from the inbound <channel> tag. end_conversation true says goodbye and closes the conversation.',
|
description: 'Speak your answer through the box; then it is their turn. Pass chat_id from the inbound <channel> tag. end_conversation true says goodbye and closes the conversation. louder changes the box\'s speaker volume, in percentage points, before it speaks this answer, so they hear the difference: 10 for "speak up", -10 for "too loud", more if they ask for a lot. The box keeps the volume within its own bounds.',
|
||||||
inputSchema: {
|
inputSchema: {
|
||||||
type: 'object',
|
type: 'object',
|
||||||
properties: { chat_id: { type: 'string' }, text: { type: 'string' }, end_conversation: { type: 'boolean' } },
|
properties: {
|
||||||
|
chat_id: { type: 'string' },
|
||||||
|
text: { type: 'string' },
|
||||||
|
end_conversation: { type: 'boolean' },
|
||||||
|
louder: { type: 'integer', minimum: -MAX_LOUDER, maximum: MAX_LOUDER },
|
||||||
|
},
|
||||||
required: ['chat_id', 'text'],
|
required: ['chat_id', 'text'],
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
@@ -77,6 +82,14 @@ const IR_TOOLS = [
|
|||||||
required: ['code'],
|
required: ['code'],
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
name: 'mute_while_listening',
|
||||||
|
description: 'Have the box mute the TV (or receiver, or sound bar) during every conversation, so it hears people over the show: it sends code when someone presses the button, and unmute_code (or code again, for a mute button that toggles) at goodbye. No code turns it off. The box cannot tell whether the TV is muted, so this is a setting, not a sensor: turn it on only with a mute code you have confirmed, and off if muting goes wrong (the TV left muted, or unmuted while listening). Changing the volume in a conversation can unmute some TVs, so that goodbye\'s toggle mutes them again: then use look, or ask, and fix it with ir_send.',
|
||||||
|
inputSchema: {
|
||||||
|
type: 'object',
|
||||||
|
properties: { code: { type: 'string' }, unmute_code: { type: 'string' } },
|
||||||
|
},
|
||||||
|
},
|
||||||
];
|
];
|
||||||
|
|
||||||
const LOOK_TOOL = {
|
const LOOK_TOOL = {
|
||||||
@@ -176,6 +189,11 @@ const main = async ({
|
|||||||
log(`ir_listen ${args.seconds}: ${JSON.stringify(heard)}`);
|
log(`ir_listen ${args.seconds}: ${JSON.stringify(heard)}`);
|
||||||
return textResult(JSON.stringify(heard));
|
return textResult(JSON.stringify(heard));
|
||||||
}
|
}
|
||||||
|
if (name === 'mute_while_listening') {
|
||||||
|
const outcome = await callIr((ir) => ir.muteWhileListening(args.code || undefined, args.unmute_code || undefined));
|
||||||
|
log(`mute_while_listening: ${outcome}`);
|
||||||
|
return textResult(outcome);
|
||||||
|
}
|
||||||
const sent = await callIr((ir) => ir.send(String(args.code ?? ''), args.times ?? 1, args.gap_ms ?? 400));
|
const sent = await callIr((ir) => ir.send(String(args.code ?? ''), args.times ?? 1, args.gap_ms ?? 400));
|
||||||
log(`ir_send: ${sent}`);
|
log(`ir_send: ${sent}`);
|
||||||
return textResult(sent);
|
return textResult(sent);
|
||||||
@@ -241,7 +259,7 @@ const main = async ({
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
if (name !== 'reply') return textResult(`no tool ${name}`, true);
|
if (name !== 'reply') return textResult(`no tool ${name}`, true);
|
||||||
const outcome = channel.reply(String(args.chat_id), String(args.text ?? ''), args.end_conversation === true);
|
const outcome = channel.reply(String(args.chat_id), String(args.text ?? ''), args.end_conversation === true, args.louder);
|
||||||
log(`reply ${args.chat_id}: ${outcome}: ${args.text}`);
|
log(`reply ${args.chat_id}: ${outcome}: ${args.text}`);
|
||||||
return textResult(outcome);
|
return textResult(outcome);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -37,6 +37,7 @@ Your body is a small box with a button, near the TV. Through it you have:
|
|||||||
- They aren't technical: be warm, plain, and brief.
|
- They aren't technical: be warm, plain, and brief.
|
||||||
- One to three short sentences.
|
- One to three short sentences.
|
||||||
- No markdown, lists, URLs, or emoji: it's all read aloud.
|
- No markdown, lists, URLs, or emoji: it's all read aloud.
|
||||||
|
- If they can't hear you ("speak up", "what?") or you're too loud, change your own volume with louder on your reply: 10 points up or down, more if they ask for a lot. That's the box's speaker, not the TV's; "turn it up" while the TV is on most likely means the TV.
|
||||||
|
|
||||||
## The remote
|
## The remote
|
||||||
|
|
||||||
@@ -46,6 +47,7 @@ You can learn and send infrared codes for anything with an IR remote: the TV, th
|
|||||||
- NEC and Samsung codes come back as hex bytes. Samsung's carry the name ("samsung E0 E0 40 BF"); a Samsung TV ignores its code sent bare. Any other remote, Sony's for one, comes back raw, as pulse lengths ("raw 2400 600 1200 ...").
|
- NEC and Samsung codes come back as hex bytes. Samsung's carry the name ("samsung E0 E0 40 BF"); a Samsung TV ignores its code sent bare. Any other remote, Sony's for one, comes back raw, as pulse lengths ("raw 2400 600 1200 ...").
|
||||||
- Send a code exactly as ir_listen reported it, every number. A raw code goes out as a short press.
|
- Send a code exactly as ir_listen reported it, every number. A raw code goes out as a short press.
|
||||||
- Use times and gap_ms to step through an on-screen menu in one call: separate ir_send calls are too slow, and the menu closes.
|
- Use times and gap_ms to step through an on-screen menu in one call: separate ir_send calls are too slow, and the menu closes.
|
||||||
|
- mute_while_listening has the box mute whatever plays the sound (the TV, or a receiver) for each conversation, so you hear people over the show. The box can't tell whether it's muted; whether the setting is on is yours to decide. Turn it on only with a confirmed mute code; if it leaves the sound off, or mutes when it should unmute, turn it off and report it. Note the setting in your workspace.
|
||||||
|
|
||||||
### Codify what you learn
|
### Codify what you learn
|
||||||
|
|
||||||
|
|||||||
+29
-13
@@ -1,6 +1,19 @@
|
|||||||
# Setting up the agent at the TV
|
# Setting up the agent at the TV
|
||||||
|
|
||||||
You'll need the [parts](../README.md#parts), a Linux home server with Nix and systemd, a private network both it and the box can join (Tailscale, by default), and an afternoon. The steps below are in the order they depend on each other. Each `make` target says more with `make help`.
|
The steps below are in the order they depend on each other. Each `make` target says more with `make help`.
|
||||||
|
|
||||||
|
## What you need
|
||||||
|
|
||||||
|
<a href="https://archive.org/details/dckc-ultimate-diy-tv-remote/PXL_20261123_033039525.jpg">
|
||||||
|
<img src="https://ia601808.us.archive.org/8/items/dckc-ultimate-diy-tv-remote/PXL_20261123_033039525_thumb.jpg" alt="electronics workbench with raspberry pi pico and IR transceiver"/>
|
||||||
|
</a>
|
||||||
|
|
||||||
|
- **The box:** a Raspberry Pi 3B with a [Google AIY Voice Kit v1](https://aiyprojects.withgoogle.com/voice-v1/) (speaker, two mics, the button).
|
||||||
|
- **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.
|
||||||
|
- **A speech server and agent host:** any Linux machine with Nix and systemd, on whenever the box is in use. It runs speech and the brain, and builds the box's image. x86_64 with AVX2 is plenty: whisper.cpp's base.en model transcribes an 11 s clip in about 2 s.
|
||||||
|
- **A private network** that the box, the speech server, and the agent host can all join: Tailscale, by default.
|
||||||
|
- **An afternoon.**
|
||||||
|
|
||||||
## 1. Make a repository for your household
|
## 1. Make a repository for your household
|
||||||
|
|
||||||
@@ -13,23 +26,25 @@ A private git repository of your own holds what's yours: the names you choose, a
|
|||||||
url = "git+https://git.inference.coop/dckc/pdtv26";
|
url = "git+https://git.inference.coop/dckc/pdtv26";
|
||||||
inputs.nixpkgs.follows = "nixpkgs";
|
inputs.nixpkgs.follows = "nixpkgs";
|
||||||
};
|
};
|
||||||
outputs = { pdtv26, ... }: {
|
outputs = { self, pdtv26, ... }: {
|
||||||
nixosConfigurations.pimote = pdtv26.lib.mkBox {
|
nixosConfigurations.pimote = pdtv26.lib.mkBox {
|
||||||
name = "pimote"; # the box's host name on your network
|
name = "pimote"; # the box's host name on your network
|
||||||
server = "den-pc"; # your home server's host name: speech and the brain
|
server = "den-pc"; # the speech server and agent host's name
|
||||||
wifi = "MyNetwork"; # your Wi-Fi network's name (SSID), spelled exactly
|
wifi = "MyNetwork"; # your Wi-Fi network's name (SSID), spelled exactly
|
||||||
admin = "pat"; # who looks after the box, and logs in to deploy
|
admin = "pat"; # who looks after the box, and logs in to deploy
|
||||||
sshKeys = [ "ssh-ed25519 AAAA... pat@laptop" ];
|
sshKeys = [ "ssh-ed25519 AAAA... pat@laptop" ];
|
||||||
};
|
};
|
||||||
|
# The box's SD card image, built on x86_64 Linux.
|
||||||
|
packages.x86_64-linux.sd-image = self.nixosConfigurations.pimote.config.system.build.sdImage;
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
Ports have defaults, and the box finds the IR emitter by its USB IDs. Anything else about the box's system goes in `modules = [ ./household.nix ]`, alongside: a status page (`pdtv26.box.statusUrl`), another Wi-Fi network, another private network (`pdtv26.box.network`), or no camera (`pdtv26.box.look.enable = false`).
|
Ports have defaults, and the box finds the IR emitter by its USB IDs. Anything else about the box's system goes in `modules = [ ./household.nix ]`, alongside: a status page (`pdtv26.box.statusUrl`), another Wi-Fi network, another private network (`pdtv26.box.network`), or no camera (`pdtv26.box.look.enable = false`).
|
||||||
|
|
||||||
## 2. Set up the home server
|
## 2. Set up the speech server
|
||||||
|
|
||||||
Any Linux with systemd and [Nix](https://nixos.org/download/) will do; it needn't be NixOS. Clone pdtv26 there, then:
|
[Install Nix](https://nixos.org/download/) if it isn't there yet. Clone pdtv26, then:
|
||||||
|
|
||||||
1. `sudo make -C speech install`: the speech server, its models (about 200 MB), its key, and its systemd unit.
|
1. `sudo make -C speech install`: the speech server, its models (about 200 MB), its key, and its systemd unit.
|
||||||
2. `sudo make -C status install BOX=pimote`: the status page, if you want one.
|
2. `sudo make -C status install BOX=pimote`: the status page, if you want one.
|
||||||
@@ -38,23 +53,24 @@ The brain comes after the box, in step 5, since it needs the box's keys.
|
|||||||
|
|
||||||
## 3. Make the box's SD card
|
## 3. Make the box's SD card
|
||||||
|
|
||||||
On any Linux machine with Nix that can run ARM programs (on Debian or Ubuntu, `apt install qemu-user-static`), in pdtv26's `box/`:
|
The image carries your household's names, so it's built from your household repository, on any Linux machine with Nix that can run ARM programs (on Debian or Ubuntu, `apt install qemu-user-static`). The Wi-Fi passphrase and the keys stay out of it.
|
||||||
|
|
||||||
1. `make image FLAKE=path/to/household BOX=pimote`, then `make card DEV=/dev/sdX` to check you have the right device, and `make flash DEV=/dev/sdX CONFIRM=erase`.
|
1. In your household repository: `nix build --option extra-platforms aarch64-linux .#sd-image`.
|
||||||
2. `make wifi-secret SSID=MyNetwork`: it puts the network's PSK on the card from the passphrase in your desktop keyring, not in the image or the repository. Store the passphrase there once, with `secret-tool store --label="Wi-Fi MyNetwork" service wifi ssid MyNetwork`.
|
2. In pdtv26's `box/`: `make card DEV=/dev/sdX` to check you have the right device, then `make flash DEV=/dev/sdX IMG=path/to/household/result/sd-image/*.img CONFIRM=erase`.
|
||||||
3. Put the card in the Pi, plug in the IR emitter's USB cord, and power it up.
|
3. Also in `box/`: `make wifi-secret SSID=MyNetwork`: it puts the network's PSK on the card from the passphrase in your desktop keyring, not in the image or the repository. Store the passphrase there once, with `secret-tool store --label="Wi-Fi MyNetwork" service wifi ssid MyNetwork`.
|
||||||
|
4. Put the card in the Pi, plug in the IR emitter's USB cord, and power it up.
|
||||||
|
|
||||||
After this, changes to the box go over ssh: `make deploy FLAKE=path/to/household BOX=pimote`.
|
After this, changes to the box go over ssh, from your household repository: `nixos-rebuild switch --flake .#pimote --target-host pat@pimote.local --sudo --option extra-platforms aarch64-linux`.
|
||||||
|
|
||||||
## 4. Join the private network
|
## 4. Join the private network
|
||||||
|
|
||||||
On the box and the home server: `tailscale up`, or whatever private network you use.
|
On the box, the speech server, and the agent host: `tailscale up`, or whatever private network you use.
|
||||||
|
|
||||||
## 5. Make the keys, and start the brain
|
## 5. Make the keys, and start the brain
|
||||||
|
|
||||||
On the home server, as the user the brain will run as, in pdtv26's `box/`:
|
On the agent host, as the user the brain will run as, in pdtv26's `box/`:
|
||||||
|
|
||||||
1. `make keys BOX=pimote ADMIN=pat`: one key per connection, piped to both its ends; the box's ir and look keys come back for the brain. Put the camera's RTSP URL in `~/.config/pdtv26-camera/rtsp-url` first, or skip `rtsp-url`.
|
1. `make keys BOX=pimote ADMIN=pat`: one key per connection, piped to both its ends; the box's ir and look keys come back for the brain. Put the camera's RTSP URL in `~/.config/pdtv26-camera/rtsp-url` first, or skip `rtsp-url`. If speech runs on another host, add `SPEECH=` that host: its key comes over ssh.
|
||||||
2. Make a fine-grained GitHub token for one repository, Issues read/write only, for problem reports, and save it as `~/.config/pdtv26-brain/report-token`.
|
2. Make a fine-grained GitHub token for one repository, Issues read/write only, for problem reports, and save it as `~/.config/pdtv26-brain/report-token`.
|
||||||
3. `make -C ../brain install BOX=pimote REPO=you/your-repo ASSIGNEE=you`, then `make -C ../brain attach` once: log in, trust the folder, and approve the box's channel.
|
3. `make -C ../brain install BOX=pimote REPO=you/your-repo ASSIGNEE=you`, then `make -C ../brain attach` once: log in, trust the folder, and approve the box's channel.
|
||||||
|
|
||||||
|
|||||||
+1
-1
@@ -14,7 +14,7 @@ SPEECH = localhost:8024
|
|||||||
BRAIN = localhost:8025
|
BRAIN = localhost:8025
|
||||||
# The private network's addresses: the only ones it answers or checks. A tailnet's, by default.
|
# The private network's addresses: the only ones it answers or checks. A tailnet's, by default.
|
||||||
RANGES = 100.64.0.0/10 fd7a:115c:a1e0::/48
|
RANGES = 100.64.0.0/10 fd7a:115c:a1e0::/48
|
||||||
APP = /var/lib/pdtv26-status/app
|
APP = /usr/local/lib/pdtv26-status/app
|
||||||
UNIT = /etc/systemd/system/pdtv26-status.service
|
UNIT = /etc/systemd/system/pdtv26-status.service
|
||||||
TARGETS = /etc/pdtv26-status/targets
|
TARGETS = /etc/pdtv26-status/targets
|
||||||
|
|
||||||
|
|||||||
+7
-1
@@ -6,7 +6,7 @@ stdenvNoCC.mkDerivation {
|
|||||||
version = "0.1.0";
|
version = "0.1.0";
|
||||||
src = lib.fileset.toSource {
|
src = lib.fileset.toSource {
|
||||||
root = ./.;
|
root = ./.;
|
||||||
fileset = lib.fileset.unions [ ./status.js ./status.test.js ./status-server.js ];
|
fileset = lib.fileset.unions [ ./status.js ./status.test.js ./status-server.js ./pdtv26-status.service ];
|
||||||
};
|
};
|
||||||
nativeCheckInputs = [ nodejs-slim ];
|
nativeCheckInputs = [ nodejs-slim ];
|
||||||
doCheck = true;
|
doCheck = true;
|
||||||
@@ -14,6 +14,12 @@ stdenvNoCC.mkDerivation {
|
|||||||
runHook preCheck
|
runHook preCheck
|
||||||
node --check status-server.js
|
node --check status-server.js
|
||||||
node --test
|
node --test
|
||||||
|
# With DynamicUser, systemd makes /var/lib/<StateDirectory> its own symlink, so nothing else
|
||||||
|
# can live there: the app (make install's GC root) goes elsewhere.
|
||||||
|
state=$(sed -n 's/^StateDirectory=//p' pdtv26-status.service)
|
||||||
|
if grep -q "^ExecStart=/var/lib/$state/" pdtv26-status.service; then
|
||||||
|
echo "pdtv26-status.service runs a program from its own StateDirectory, /var/lib/$state" >&2; exit 1
|
||||||
|
fi
|
||||||
runHook postCheck
|
runHook postCheck
|
||||||
'';
|
'';
|
||||||
installPhase = ''
|
installPhase = ''
|
||||||
|
|||||||
@@ -8,7 +8,7 @@ Wants=network-online.target
|
|||||||
# speech server, and the brain's channel; make install writes them, host:port, to the targets file.
|
# speech server, and the brain's channel; make install writes them, host:port, to the targets file.
|
||||||
# The private network is the boundary: no key.
|
# The private network is the boundary: no key.
|
||||||
EnvironmentFile=/etc/pdtv26-status/targets
|
EnvironmentFile=/etc/pdtv26-status/targets
|
||||||
ExecStart=/var/lib/pdtv26-status/app/bin/status-server :: ${PORT} /var/lib/pdtv26-status ${NAME} ${BOX} ${SPEECH} ${BRAIN}
|
ExecStart=/usr/local/lib/pdtv26-status/app/bin/status-server :: ${PORT} /var/lib/pdtv26-status ${NAME} ${BOX} ${SPEECH} ${BRAIN}
|
||||||
DynamicUser=yes
|
DynamicUser=yes
|
||||||
StateDirectory=pdtv26-status
|
StateDirectory=pdtv26-status
|
||||||
IPAddressDeny=any
|
IPAddressDeny=any
|
||||||
|
|||||||
+7
-3
@@ -24,7 +24,7 @@ const fromButton = (source) => source.endsWith('-button');
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* @typedef {{ at: number, kind: string, source: string, reason?: string, code?: string, times?: number }} Event
|
* @typedef {{ at: number, kind: string, source: string, reason?: string, code?: string, times?: number }} Event
|
||||||
* @typedef {{ name: string, up: boolean, at: number, since: number }} Check
|
* @typedef {{ name: string, up: boolean, at: number, since: number, outage?: number }} Check outage: when the latest outage we saw began
|
||||||
* @typedef {{ conversations: number, turns: number, huh: number, interrupts: number, irPresses: number, looks: number }} Tally
|
* @typedef {{ conversations: number, turns: number, huh: number, interrupts: number, irPresses: number, looks: number }} Tally
|
||||||
* @typedef {{ word: string, since?: number, why?: string }} State
|
* @typedef {{ word: string, since?: number, why?: string }} State
|
||||||
* @typedef {{ state: State, heartbeat?: number, checks: (typeof CHECKS[number] & Partial<Check>)[], today: Tally, total: Tally, recent: Event[] }} Summary
|
* @typedef {{ state: State, heartbeat?: number, checks: (typeof CHECKS[number] & Partial<Check>)[], today: Tally, total: Tally, recent: Event[] }} Summary
|
||||||
@@ -82,7 +82,9 @@ export class Status {
|
|||||||
/** @param {string} name @param {boolean} up @param {number} at */
|
/** @param {string} name @param {boolean} up @param {number} at */
|
||||||
check(name, up, at) {
|
check(name, up, at) {
|
||||||
const prev = this.#checks.get(name);
|
const prev = this.#checks.get(name);
|
||||||
this.#checks.set(name, { name, up, at, since: prev && prev.up === up ? prev.since : at });
|
const since = prev && prev.up === up ? prev.since : at;
|
||||||
|
const outage = up ? prev?.outage : since;
|
||||||
|
this.#checks.set(name, { name, up, at, since, ...(outage === undefined ? {} : { outage }) });
|
||||||
}
|
}
|
||||||
|
|
||||||
size() { return this.#events.length; }
|
size() { return this.#events.length; }
|
||||||
@@ -93,7 +95,9 @@ export class Status {
|
|||||||
if (!up) return { word: 'not checked yet' };
|
if (!up) return { word: 'not checked yet' };
|
||||||
if (!up.up) return { word: 'unreachable', since: up.since };
|
if (!up.up) return { word: 'unreachable', since: up.since };
|
||||||
const ready = this.#events.findLast((e) => e.kind === 'ready');
|
const ready = this.#events.findLast((e) => e.kind === 'ready');
|
||||||
if (!ready || ready.at < up.since) return { word: 'booting', since: up.since };
|
// Services restart together, so ready can come before the check sees the box up again: a ready
|
||||||
|
// counts unless it's from before the latest outage we saw.
|
||||||
|
if (!ready || ready.at < (up.outage ?? -Infinity)) return { word: 'booting', since: up.since };
|
||||||
const alive = Math.max(this.#heartbeat ?? 0, this.#events.findLast((e) => fromButton(e.source))?.at ?? 0);
|
const alive = Math.max(this.#heartbeat ?? 0, this.#events.findLast((e) => fromButton(e.source))?.at ?? 0);
|
||||||
if (now - alive > 3 * HEARTBEAT_MS) return { word: 'not responding', since: alive, why: 'no heartbeat from its button service' };
|
if (now - alive > 3 * HEARTBEAT_MS) return { word: 'not responding', since: alive, why: 'no heartbeat from its button service' };
|
||||||
const last = this.#events.findLast((e) => e.kind === 'conversation' || e.kind === 'end');
|
const last = this.#events.findLast((e) => e.kind === 'conversation' || e.kind === 'end');
|
||||||
|
|||||||
@@ -41,6 +41,24 @@ test('a ready from before the box went away does not count: booting', () => {
|
|||||||
assert.equal(s.summary(4 * MIN).state.word, 'booting');
|
assert.equal(s.summary(4 * MIN).state.word, 'booting');
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test('a ready during the outage counts: services restart together, and the check sees the box up last', () => {
|
||||||
|
const s = new Status(dayOf);
|
||||||
|
s.check('box', true, 0);
|
||||||
|
s.record({ at: 1 * MIN, kind: 'ready', source: 'pdtv26-button' });
|
||||||
|
s.check('box', false, 2 * MIN);
|
||||||
|
s.record({ at: 2.5 * MIN, kind: 'ready', source: 'pdtv26-button' });
|
||||||
|
s.check('box', true, 3 * MIN);
|
||||||
|
assert.deepEqual(s.summary(4 * MIN).state, { word: 'ready for duty', since: 2.5 * MIN });
|
||||||
|
});
|
||||||
|
|
||||||
|
test('a ready from before the server started counts, if the server saw no outage', () => {
|
||||||
|
const s = new Status(dayOf);
|
||||||
|
s.record({ at: 1 * MIN, kind: 'ready', source: 'pdtv26-button' });
|
||||||
|
s.check('box', true, 10 * MIN);
|
||||||
|
s.beat(10.5 * MIN);
|
||||||
|
assert.deepEqual(s.summary(11 * MIN).state, { word: 'ready for duty', since: 1 * MIN });
|
||||||
|
});
|
||||||
|
|
||||||
test('checks keep when they last changed', () => {
|
test('checks keep when they last changed', () => {
|
||||||
const s = new Status(dayOf);
|
const s = new Status(dayOf);
|
||||||
s.check('brain', true, 1 * MIN);
|
s.check('brain', true, 1 * MIN);
|
||||||
|
|||||||
Reference in new issue
Block a user