Files
pdtv26/box/ir-server.js
T
dckc 521998b666
check / check (push) Canceled after 0s
feat(box): the box's NixOS system as a module, and lib.mkBox from a few names
The box within reach of the couch: a Raspberry Pi 3B with the AIY Voice
HAT, from the first household's configuration, made generic.

- box/body: the button service, in Python: press and talk, turns by
  voice, a press interrupts; the look signal
- box/*.js: the ir and look capabilities, behind gates, for the brain;
  the ask client, the box's side of a conversation
- box/module.nix: the services, each confined to the devices and
  addresses it needs; the private network as an option (a tailnet by
  default); the Pico found by its USB IDs, as /dev/pdtv26-ir
- box/voicehat.nix: the Voice HAT's device tree overlay and ALSA setup
- lib.mkBox: a box's whole system from its name, the home server's,
  the Wi-Fi network's, and who looks after it
- checks: box-js, box-py (doctests and pyflakes), and box-system (an
  example box's system evaluates)

Generated-by: Claude Opus 5.5
2026-12-02 16:18:17 -06:00

76 lines
3.2 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.
*/
import { newWebSocketRpcSession } from 'capnweb';
import { spawn as spawnChild } from 'node:child_process';
import { readFile } from 'node:fs/promises';
import process from 'node:process';
import { WebSocketServer } from 'ws';
import { Gate } from './gate.js';
import { Ir } from './ir.js';
import { makeCommand, timed } from './run.js';
/** The lines worth logging of what the Pico printed. */
const PICO_SAID = /^(got|sent|unparsed|bad)/;
/**
* Serve the ir capability, behind a gate, at HOST:PORT.
*
* @param {object} [io] what it reaches; the process's own, by default
* @param {string[]} [io.argv] HOST PORT PICO [STATUS_URL]
* @param {Record<string, string | undefined>} [io.env] for CREDENTIALS_DIRECTORY
* @param {typeof readFile} [io.read] reads the key
* @param {typeof spawnChild} [io.spawn] runs PICO, and nothing else
* @param {typeof fetch} [io.post] reaches STATUS_URL, and nothing else
* @param {() => number} [io.now] the clock, for timing jobs
* @param {(options: import('ws').ServerOptions) => WebSocketServer} [io.listen]
* @param {typeof newWebSocketRpcSession} [io.serve] serves the gate on one connection
*/
const main = async ({
argv = process.argv.slice(2),
env = process.env,
read = readFile,
spawn = spawnChild,
post = fetch,
now = Date.now,
listen = (options) => new WebSocketServer(options),
serve = newWebSocketRpcSession,
} = {}) => {
const [host, port, pico, statusUrl] = argv;
const key = (await read(`${env.CREDENTIALS_DIRECTORY}/ir-key`, 'utf8')).trim();
/**
* Tell the status page, if any; a failure there is logged, never the send's failure.
* @param {object} event
*/
const report = (event) => {
if (!statusUrl) return;
post(`${statusUrl}/event`, {
method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ source: 'pdtv26-ir', ...event }),
}).then((res) => { if (!res.ok) console.error(`status: ${res.status}`); }, (err) => console.error(`status: ${err.message}`));
};
const ir = new Ir(async (args) => {
const out = await timed(now, `pico ${args.join(' ')}`,
async () => (await makeCommand(spawn, pico, args)('')).toString(),
(o) => o.trim().split('\n').filter((ln) => PICO_SAID.test(ln)).join('; ') || '(nothing)');
if (args[0] === 'repeat') report({ kind: 'ir', code: args.slice(3).join(' '), times: Number(args[1]) });
return out;
});
const gate = new Gate(key, ir);
const wss = listen({ host, port: Number(port), maxPayload: 64 * 1024 });
wss.on('connection', (ws, req) => {
console.log(`connection from ${req.socket.remoteAddress}`);
serve(ws, gate);
});
console.log(`ir-server: listening on ${host}:${port}`);
};
main().catch((err) => {
console.error(err);
process.exitCode = 1;
});