#!/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} [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; });