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
117 lines
5.4 KiB
JavaScript
Executable File
117 lines
5.4 KiB
JavaScript
Executable File
#!/usr/bin/env node
|
|
/**
|
|
* @file ir-server: the ir capability over Cap'n Web, behind a gate, for the brain.
|
|
* usage: ir-server.js HOST PORT PICO [STATUS_URL]
|
|
* PICO VERB ARGS... talks to the Pico: listen SECONDS, repeat N GAP_MS CODE... (../ir-pico/pico_tty.py, its tty bound in).
|
|
* STATUS_URL, if any, is a status page, told of each send, for its count of IR presses.
|
|
* The key is in $CREDENTIALS_DIRECTORY/ir-key (systemd LoadCredential), not argv, where ps would show it.
|
|
*
|
|
* 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 { spawn as spawnChild } from 'node:child_process';
|
|
import { readFile, writeFile } from 'node:fs/promises';
|
|
import { createServer } from 'node:net';
|
|
import process from 'node:process';
|
|
import { WebSocketServer } from 'ws';
|
|
import { Gate } from './gate.js';
|
|
import { Ir, Muting } from './ir.js';
|
|
import { makeCommand, timed } from './run.js';
|
|
|
|
/** The lines worth logging of what the Pico printed. */
|
|
const PICO_SAID = /^(got|sent|unparsed|bad)/;
|
|
|
|
/**
|
|
* Serve the ir capability, behind a gate, at HOST:PORT.
|
|
*
|
|
* @param {object} [io] what it reaches; the process's own, by default
|
|
* @param {string[]} [io.argv] HOST PORT PICO [STATUS_URL]
|
|
* @param {Record<string, string | undefined>} [io.env] for CREDENTIALS_DIRECTORY
|
|
* @param {typeof readFile} [io.read] reads the key 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 fetch} [io.post] reaches STATUS_URL, and nothing else
|
|
* @param {() => number} [io.now] the clock, for timing jobs
|
|
* @param {(options: import('ws').ServerOptions) => WebSocketServer} [io.listen]
|
|
* @param {typeof newWebSocketRpcSession} [io.serve] serves the gate on one connection
|
|
*/
|
|
const main = async ({
|
|
argv = process.argv.slice(2),
|
|
env = process.env,
|
|
read = readFile,
|
|
write = writeFile,
|
|
serveLocal = createServer,
|
|
pid = () => process.pid,
|
|
spawn = spawnChild,
|
|
post = fetch,
|
|
now = Date.now,
|
|
listen = (options) => new WebSocketServer(options),
|
|
serve = newWebSocketRpcSession,
|
|
} = {}) => {
|
|
const [host, port, pico, statusUrl] = argv;
|
|
const key = (await read(`${env.CREDENTIALS_DIRECTORY}/ir-key`, 'utf8')).trim();
|
|
/**
|
|
* Tell the status page, if any; a failure there is logged, never the send's failure.
|
|
* @param {object} event
|
|
*/
|
|
const report = (event) => {
|
|
if (!statusUrl) return;
|
|
post(`${statusUrl}/event`, {
|
|
method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ source: 'pdtv26-ir', ...event }),
|
|
}).then((res) => { if (!res.ok) console.error(`status: ${res.status}`); }, (err) => console.error(`status: ${err.message}`));
|
|
};
|
|
const 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 out = await timed(now, `pico ${args.join(' ')}`,
|
|
async () => (await makeCommand(spawn, pico, args)('')).toString(),
|
|
(o) => o.trim().split('\n').filter((ln) => PICO_SAID.test(ln)).join('; ') || '(nothing)');
|
|
if (args[0] === 'repeat') report({ kind: 'ir', code: args.slice(3).join(' '), times: Number(args[1]) });
|
|
return out;
|
|
}, muting);
|
|
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 });
|
|
wss.on('connection', (ws, req) => {
|
|
console.log(`connection from ${req.socket.remoteAddress}`);
|
|
serve(ws, gate);
|
|
});
|
|
console.log(`ir-server: listening on ${host}:${port}`);
|
|
};
|
|
|
|
main().catch((err) => {
|
|
console.error(err);
|
|
process.exitCode = 1;
|
|
});
|