/** * @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:')) }; }; /** * A code as send takes it, normalized; or a TypeError. * @param {unknown} code */ export const checkCode = (code) => { 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`); } return norm; }; /** @typedef {{ mute: string, unmute: string }} MuteCodes */ /** * Whether to mute the TV while the box listens: a setting, and nothing sensed. Mute is often a toggle, * and a camera can't reliably tell whether the TV is muted, so whoever holds the ir capability * turns this on or off, and the box doesn't guess. */ export class Muting { /** @type {MuteCodes | undefined} */ #codes; #save; /** * @param {unknown} saved what save was last given, if anything * @param {(codes: MuteCodes | undefined) => Promise} save keeps the setting across restarts */ constructor(saved, save) { const s = /** @type {any} */ (saved); this.#codes = s?.mute ? { mute: checkCode(s.mute), unmute: checkCode(s.unmute ?? s.mute) } : undefined; this.#save = save; } /** * Turn it on, with the code that mutes (and the one that unmutes, if not the same); or off, with no code. * @param {string} [code] @param {string} [unmuteCode] */ async set(code, unmuteCode) { if (!code) { this.#codes = undefined; await this.#save(undefined); return 'off: the box no longer mutes anything while it listens'; } const codes = { mute: checkCode(code), unmute: unmuteCode ? checkCode(unmuteCode) : checkCode(code) }; this.#codes = codes; await this.#save(codes); return codes.mute === codes.unmute ? `on: the box sends ${codes.mute} when a conversation starts, and again when it ends` : `on: the box sends ${codes.mute} when a conversation starts, and ${codes.unmute} when it ends`; } /** @returns {MuteCodes | undefined} */ get codes() { return this.#codes; } /** * A conversation starts: mute, if the setting is on. Resolves to what unmutes at its end, with the * codes it muted with, even if the setting changes meanwhile. * @param {(code: string) => Promise} send * @returns {Promise<() => Promise>} */ async start(send) { const codes = this.#codes; if (!codes) return async () => 'muting is off'; await send(codes.mute); return () => send(codes.unmute); } } /** * 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} the job before this one */ #last = Promise.resolve(); #muting; /** * @param {(args: string[]) => Promise} pico runs pico_tty.py's verbs: listen SECONDS, repeat N GAP_MS CODE... * @param {Muting} [muting] whether to mute the TV while the box listens */ constructor(pico, muting = undefined) { super(); this.#pico = pico; this.#muting = muting; } /** * Mute the TV while the box listens, with these codes; or, with no code, don't. * @param {string} [code] @param {string} [unmuteCode] if not the same: mute is often a toggle */ muteWhileListening(code, unmuteCode) { if (!this.#muting) throw new Error('this box has no mute setting'); return this.#muting.set(code, unmuteCode); } /** * @template T * @param {() => Promise} job * @returns {Promise} */ #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 = checkCode(code); 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`; }); } }