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