macotron.appletv
Find Apple TVs on the local network, pair with one using the PIN it shows, and press keys on its remote. Macotron uses the Companion protocol, the one the iPhone remote uses.
const [tv] = await macotron.appletv.list();
if (!macotron.appletv.paired(tv.id)) {
await macotron.appletv.pair(tv.id); // the TV shows a PIN
const pin = macotron.prompt(`PIN shown on ${tv.name}`);
const result = await macotron.appletv.pair(tv.id, pin);
if (!result.ok) throw new Error(result.error);
}
await macotron.appletv.send(tv.id, "select");
Finding devices
list(): Promise<Array<{ id, name, host, port, type }>>
Browses Bonjour for _companion-link._tcp and _airplay._tcp for 1.5 seconds and resolves with what it finds. id is "host:port", type is the service type, and name is the name set on the device.
Macotron reuses a result for 30 seconds, so repeated calls return at once. An empty result is not reused.
Every device that offers either service shows up, so the list can include AirPlay speakers, smart TVs, and Macs as well as Apple TVs. One Apple TV usually appears twice, once per service, with a different port in each id. Either id works with the calls below. Group rows by host or name for a picker. macOS asks for Local Network permission the first time Macotron browses.
Pairing
pair(id: string, pin?: string): Promise<{ ok: boolean; error?: string }>
Pairing takes two calls. pair(id) starts it, and the TV shows a 4-digit PIN. pair(id, pin) finishes it with that PIN and stores the pairing in the Keychain. The TV then lists Macotron under Settings > Remotes and Devices.
Errors include "Wrong PIN", "Call pair(id) first so the TV shows a PIN", "The PIN is the 4 numbers on the TV", "No Companion service" (the TV does not offer _companion-link._tcp), and "No Apple TV".
paired(id: string): boolean
Whether this Mac has a pairing stored for the TV. Pairings are kept by the TV's name, so renaming the TV means pairing again.
unpair(id: string): void
Forgets the pairing on this Mac. The TV keeps its side until you remove Macotron in Settings > Remotes and Devices.
Remote keys
send(id: string, command: "up" | "down" | "left" | "right" | "select" | "menu" | "home" | "play" | "pause" | "playpause"): Promise<{ ok: boolean; error?: string }>
Presses and releases a key on the paired TV. The first key opens a connection, and later keys reuse it. Without a pairing it resolves { ok: false, error: "not paired" }. If you removed Macotron on the TV, it resolves an error that says to pair again.
See also
- macotron.bonjour to browse for other service types.
- macotron.media to control playback on the Mac itself.
- The
apple-tv.jsplugin, which builds the remote panel and the Pair Apple TV command.