Files
pdtv26/box/look-server.js
T
dckc 190600a696 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 18:57:03 -06:00

82 lines
3.5 KiB
JavaScript
Executable File

#!/usr/bin/env node
/**
* @file look-server: the look capability over Cap'n Web, behind a gate, for the brain.
* usage: look-server.js HOST PORT SIGNAL_SOCKET FFMPEG
* SIGNAL_SOCKET is the button service's: while a connection to it is open, the box shows it's looking.
* The key is in $CREDENTIALS_DIRECTORY/look-key, and the camera's RTSP URL, password and all,
* in $CREDENTIALS_DIRECTORY/rtsp-url (systemd LoadCredential).
*/
import { newWebSocketRpcSession } from 'capnweb';
import { spawn as spawnChild } from 'node:child_process';
import { readFile } from 'node:fs/promises';
import { createConnection } from 'node:net';
import process from 'node:process';
import { WebSocketServer } from 'ws';
import { Gate } from './gate.js';
import { Look } from './look.js';
import { makeCommand, timed } from './run.js';
/**
* Connect to the button service and wait for "looking"; resolve to a function that ends the connection.
*
* @param {() => import('node:net').Socket} connect opens a connection to the button service's socket, and no other
*/
const signalVia = (connect) => () => new Promise((resolve, reject) => {
const conn = connect();
/** @param {Error} err */
const fail = (err) => { conn.destroy(); reject(new Error(`the box can't show it's looking: ${err.message}`)); };
conn.setTimeout(5000, () => fail(new Error('no answer in 5 s')));
conn.on('error', fail);
conn.on('data', (d) => {
if (!d.toString().startsWith('looking')) return;
conn.setTimeout(0);
resolve(() => conn.end());
});
});
/**
* Serve the look capability, behind a gate, at HOST:PORT.
*
* @param {object} [io] what it reaches; the process's own, by default
* @param {string[]} [io.argv] HOST PORT SIGNAL_SOCKET FFMPEG
* @param {Record<string, string | undefined>} [io.env] for CREDENTIALS_DIRECTORY
* @param {typeof readFile} [io.read] reads the key and the camera's URL
* @param {typeof spawnChild} [io.spawn] runs FFMPEG, and nothing else
* @param {typeof createConnection} [io.connect] reaches SIGNAL_SOCKET, and nothing else
* @param {() => number} [io.now] the clock, for timing looks
* @param {(options: import('ws').ServerOptions) => WebSocketServer} [io.listen]
* @param {typeof newWebSocketRpcSession} [io.serve] serves the gate on one connection
*/
const main = async ({
argv = process.argv.slice(2),
env = process.env,
read = readFile,
spawn = spawnChild,
connect = createConnection,
now = Date.now,
listen = (options) => new WebSocketServer(options),
serve = newWebSocketRpcSession,
} = {}) => {
const [host, port, socketPath, ffmpeg] = argv;
/** @param {string} name */
const cred = async (name) => (await read(`${env.CREDENTIALS_DIRECTORY}/${name}`, 'utf8')).trim();
const [key, url] = [await cred('look-key'), await cred('rtsp-url')];
// One frame, 1280 wide: plenty to read a TV screen, and fewer tokens than 1920.
const grabOne = makeCommand(spawn, ffmpeg, ['-v', 'error', '-rtsp_transport', 'tcp', '-timeout', '10000000',
'-i', url, '-frames:v', '1', '-vf', 'scale=1280:-2', '-q:v', '4', '-f', 'image2pipe', '-c:v', 'mjpeg', '-']);
const look = new Look(signalVia(() => connect(socketPath)),
() => timed(now, 'look', () => grabOne(''), (jpeg) => `${jpeg.length} bytes`));
const gate = new Gate(key, look);
const wss = listen({ host, port: Number(port), maxPayload: 64 * 1024 });
wss.on('connection', (ws, req) => {
console.log(`connection from ${req.socket.remoteAddress}`);
serve(ws, gate);
});
console.log(`look-server: listening on ${host}:${port}`);
};
main().catch((err) => {
console.error(err);
process.exitCode = 1;
});