feat: mute the TV while the box listens, if the brain turns that on
check / check (push) Waiting to run
check / check (push) Waiting to run
whisper hears people better without the show behind them. The brain sets a mute code (and an unmute code, if not the same) with mute_while_listening on its ir capability, or turns it off; ir-server keeps the setting in its state directory. Mute is often a toggle, and the camera can't reliably tell whether the sound is off, so the box senses nothing: the setting is the brain's to turn on or off. The button service holds a connection to ir-server's conversation socket for each conversation: ir-server mutes when it opens and unmutes, with the same codes, when it closes. The socket's group is the button's alone, and the button still can't send any code. Generated-by: Claude Opus 5.5
This commit is contained in:
1 parent
5191ee9931
commit
f50c871521
10 files changed
+269
-22
No files matched your search
+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.
|
||||||
|
|
||||||
|
|||||||
+14
-8
@@ -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), the volume (mixer.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
|
||||||
@@ -28,6 +29,7 @@ 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 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
|
||||||
|
|
||||||
@@ -46,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 AMIXER 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, amixer, 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()
|
||||||
|
|
||||||
@@ -69,6 +72,7 @@ async def main(argv, environ, getpid, cwd, request_lines, socket, create_subproc
|
|||||||
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
|
||||||
@@ -89,9 +93,10 @@ 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")
|
||||||
await converse(convo, partial(mics.listen, button=button), hear.transcribe, brain.ask,
|
async with muting.during():
|
||||||
voice.speak, speaker.play, mixer.louder, light.mics, light.thinking, brain.end,
|
await converse(convo, partial(mics.listen, button=button), hear.transcribe, brain.ask,
|
||||||
logging.info, note)
|
voice.speak, speaker.play, mixer.louder, light.mics, light.thinking, brain.end,
|
||||||
|
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:
|
||||||
if task.done():
|
if task.done():
|
||||||
@@ -114,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,
|
||||||
))
|
))
|
||||||
|
|
||||||
|
|||||||
@@ -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/);
|
||||||
|
});
|
||||||
+15
-1
@@ -117,7 +117,7 @@ in
|
|||||||
"${pkgs.alsa-utils}/bin/aplay" "${pkgs.alsa-utils}/bin/amixer" "${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
@@ -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:
|
||||||
|
|||||||
@@ -82,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 = {
|
||||||
@@ -181,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);
|
||||||
|
|||||||
@@ -47,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
|
||||||
|
|
||||||
|
|||||||
Reference in new issue
Block a user