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
125 lines
4.9 KiB
JavaScript
125 lines
4.9 KiB
JavaScript
/**
|
|
* @file The ir capability: learn and send infrared remote codes through the Pico on the box's USB.
|
|
* Who can work the TV, the cable box, or anything else with an IR remote is who holds an Ir.
|
|
* @see ../ir-pico/pico_tty.py, the Pico's side
|
|
*/
|
|
import { RpcTarget } from 'capnweb';
|
|
|
|
/** Long enough to find the remote and press a button or two. */
|
|
export const MAX_LISTEN_SECONDS = 60;
|
|
|
|
/** Enough presses to step through any on-screen menu. */
|
|
export const MAX_TIMES = 20;
|
|
|
|
/** NEC codes are 4 bytes; leave room for longer ones. Samsung's carry its name. */
|
|
const CODE = /^(samsung )?[0-9A-F]{2}( [0-9A-F]{2}){0,15}$/;
|
|
|
|
/** Pulses the Pico keeps of a burst (ir_commands.MAX_RAW). */
|
|
export const MAX_RAW = 199;
|
|
|
|
/** Any other remote's burst: mark and space lengths in microseconds, mark first and last. */
|
|
const RAW = /^raw [1-9][0-9]{0,4}( [1-9][0-9]{0,4})*$/;
|
|
|
|
/** @param {string} code */
|
|
const isRaw = (code) => {
|
|
if (!RAW.test(code)) return false;
|
|
const us = code.split(' ').slice(1).map(Number);
|
|
return us.length % 2 === 1 && us.length <= MAX_RAW && us.every((n) => n <= 65535);
|
|
};
|
|
|
|
/**
|
|
* Two raw frames of one button: as many pulses, each within a fifth.
|
|
* @param {string} a
|
|
* @param {string} b
|
|
*/
|
|
const sameRaw = (a, b) => {
|
|
const [as, bs] = [a.split(' '), b.split(' ')];
|
|
return as.length === bs.length
|
|
&& as.every((x, i) => i === 0 || Math.abs(+x - +bs[i]) <= 0.2 * Math.max(+x, +bs[i]));
|
|
};
|
|
|
|
/**
|
|
* "Samsung e0 e0 40 bf" => "samsung E0 E0 40 BF": names in lower case, bytes in upper.
|
|
* @param {string} code
|
|
*/
|
|
const normalize = (code) =>
|
|
code.trim().split(/\s+/).map((w) => (/^[a-z]{3,}$/i.test(w) ? w.toLowerCase() : w.toUpperCase())).join(' ');
|
|
|
|
/**
|
|
* Sort what the Pico printed: "got 20 DF 10 EF" is a code it decoded (NEC;
|
|
* Samsung's come named: "got samsung E0 E0 40 BF"); any other remote's comes raw,
|
|
* "got raw 2400 600 1200 ...", and a held button's run of raw frames counts once;
|
|
* "unparsed: ..." is a burst too short to be a code (noise).
|
|
* @param {string} out
|
|
* @returns {{ codes: string[], unparsed: string[] }}
|
|
*/
|
|
export const parseHeard = (out) => {
|
|
const lines = out.split('\n').map((ln) => ln.trim());
|
|
/** @type {string[]} */
|
|
const codes = [];
|
|
for (const code of lines.filter((ln) => ln.startsWith('got ')).map((ln) => ln.slice(4))) {
|
|
const prev = codes.at(-1);
|
|
if (!(prev?.startsWith('raw ') && code.startsWith('raw ') && sameRaw(prev, code))) codes.push(code);
|
|
}
|
|
return { codes, unparsed: lines.filter((ln) => ln.startsWith('unparsed:')) };
|
|
};
|
|
|
|
/**
|
|
* listen(seconds) reports the codes a remote sent meanwhile; send(code, times, gapMs) sends one,
|
|
* times times, gapMs apart: quick enough that a TV's input menu stays open between presses.
|
|
* One at a time: there's one Pico, and listening while sending hears our own echo.
|
|
*/
|
|
export class Ir extends RpcTarget {
|
|
#pico;
|
|
/** @type {Promise<unknown>} the job before this one */
|
|
#last = Promise.resolve();
|
|
|
|
/** @param {(args: string[]) => Promise<string>} pico runs pico_tty.py's verbs: listen SECONDS, repeat N GAP_MS CODE... */
|
|
constructor(pico) {
|
|
super();
|
|
this.#pico = pico;
|
|
}
|
|
|
|
/**
|
|
* @template T
|
|
* @param {() => Promise<T>} job
|
|
* @returns {Promise<T>}
|
|
*/
|
|
#inTurn(job) {
|
|
const result = this.#last.then(job);
|
|
this.#last = result.catch(() => {});
|
|
return result;
|
|
}
|
|
|
|
/** @param {number} seconds */
|
|
listen(seconds) {
|
|
if (!Number.isInteger(seconds) || seconds < 1 || seconds > MAX_LISTEN_SECONDS) {
|
|
throw new RangeError(`seconds: a whole number, 1 to ${MAX_LISTEN_SECONDS}`);
|
|
}
|
|
return this.#inTurn(async () => parseHeard(await this.#pico(['listen', String(seconds)])));
|
|
}
|
|
|
|
/**
|
|
* @param {string} code as listen reports it: hex bytes, "20 DF 10 EF" or "samsung E0 E0 40 BF",
|
|
* or pulses, "raw 2400 600 1200 ..." (sent as a short press: three frames)
|
|
* @param {number} [times] presses, 1 to MAX_TIMES
|
|
* @param {number} [gapMs] between presses, 100 to 2000
|
|
*/
|
|
send(code, times = 1, gapMs = 400) {
|
|
const norm = typeof code === 'string' ? normalize(code) : '';
|
|
if (!CODE.test(norm) && !isRaw(norm)) {
|
|
throw new TypeError(`code: hex bytes, like "20 DF 10 EF" or "samsung E0 E0 40 BF"; or "raw" and an odd number of microseconds, up to ${MAX_RAW}, each up to 65535`);
|
|
}
|
|
if (!Number.isInteger(times) || times < 1 || times > MAX_TIMES) {
|
|
throw new RangeError(`times: a whole number, 1 to ${MAX_TIMES}`);
|
|
}
|
|
if (!Number.isInteger(gapMs) || gapMs < 100 || gapMs > 2000) throw new RangeError('gapMs: 100 to 2000');
|
|
return this.#inTurn(async () => {
|
|
const out = await this.#pico(['repeat', String(times), String(gapMs), ...norm.split(' ')]);
|
|
const sent = out.split('\n').filter((ln) => ln.trim() === `sent ${norm}`).length;
|
|
if (sent < times) throw new Error(`the Pico confirmed ${sent} of ${times}: ${out.trim().slice(-200)}`);
|
|
return times === 1 ? `sent ${norm}` : `sent ${norm} ${times} times, ${gapMs} ms apart`;
|
|
});
|
|
}
|
|
}
|