One iPhone remote for Roku, Fire TV, Apple TV and Samsung
I had four remote apps on my phone. Roku's, Amazon's, Apple's, Samsung's. Each one wants a different swipe, each one forgets the TV it was paired with at a different moment, and every one of them is a full app launch away when all I want is to pause something. So I built one remote that drives all of them. It took an afternoon, and most of that was learning that the four TVs have almost nothing in common.
The shape: a small Python daemon on a home server talks to the TVs, the existing backend proxies it behind auth, and a SwiftUI app plus a Control Center button talk to the backend. Samsung is the exception — the phone talks to it directly. More on that below.
Four TVs, four protocols
Roku is the easy one. External Control Protocol is plain HTTP on port 8060, no pairing, no auth. A keypress is a POST:
async def key(self, key: str) -> None:
await self._post("/keypress/" + ROKU_KEYS[key])
/query/apps, /query/active-app and /query/icon/<id> give you an app grid with real icons for free. HDMI inputs show up in the same app list with type="tvin".
Fire TV is Android, so it's adb over the network. input keyevent 19 is "up". You enable ADB debugging on the device once and accept the prompt.
Apple TV goes through pyatv and the Companion protocol. Pairing is a PIN the Apple TV shows on screen; you type it into the app, and the credentials are stored server-side. AirPlay pairs the same way, right after.
Samsung Tizen TVs take a websocket on wss://<tv>:8002/api/v2/channels/samsung.remote.control. The first connect pops an "Allow" prompt on the TV; once you accept, the TV sends back a token you include on every later connect so it stops asking.
The daemon hides all of that behind one small interface — key, text, apps, launch, input, state — and a dict mapping a device's kind to its driver class.
The latency is the whole product
A remote that lags is worse than no remote, because you press again and now you've skipped two episodes. The first version opened a fresh connection per keypress and it cost 1–3 seconds. That's the pyatv handshake, or adb connect plus a new shell, every single time.
The fix is boring: keep everything warm.
For Fire TV, one long-lived adb shell stays open and each keypress is a single line written to its stdin:
self.proc.stdin.write((cmd + "\n").encode())
await self.proc.stdin.drain()
The catch is that when the TV drops off Wi-Fi, the shell doesn't necessarily die — it just quietly swallows your presses. So if the shell hasn't proven itself in the last 30 seconds, it gets an echo round trip first:
async def _alive(self) -> bool:
"""Round-trip an echo: a dropped TV link otherwise swallows presses."""
self.proc.stdin.write(b"echo __alive__\n")
await self.proc.stdin.drain()
while True:
line = await asyncio.wait_for(self.proc.stdout.readline(), 2)
if not line:
return False
if b"__alive__" in line:
self.last_ok = time.monotonic()
return True
If that fails, kill the shell, reconnect, try once more.
For Apple TV, the pyatv connection is held open per device and reused. When the app asks for the device list — which is the first thing it does on launch — the daemon kicks off a background connect to every paired Apple TV, so the connection is usually already up by the time your thumb reaches a button.
With everything warm, a press measured about 0.37 seconds round trip from the phone, through the public endpoint and back. That's fast enough that it feels like a remote.
Two things that bit me
Don't retry a press that timed out. The obvious retry loop — timeout, reconnect, send again — produces double presses, because a timeout doesn't mean the press didn't land. It often did; only the acknowledgement got lost. So timeouts drop the connection and report an error, and only actual exceptions get a second attempt:
except asyncio.TimeoutError:
# The press may already have landed; replaying it double-presses.
await self._drop()
raise DeviceError("Apple TV did not answer")
pyatv holds its listener weakly. I set a listener with a connection_lost callback so a dead connection would clear itself and reconnect on the next press. It never fired. The listener was a local object, pyatv only kept a weak reference, and it got garbage-collected right after setup. Keep a reference yourself:
# pyatv keeps listeners weakly; hold it or connection_lost never fires.
self._listener = _Listener()
atv.listener = self._listener
Volume goes to the TV, not the box
An Apple TV plugged into a Roku TV doesn't own the volume — the TV does (unless you've got HDMI-CEC behaving, which, sure). So a device can declare volume_via, and volume and mute presses on the Apple TV get routed to the TV it's plugged into:
via = drv.dev.get("volume_via")
if via and key in ("volup", "voldown", "mute"):
target = hub.driver(via)
The same config can say "when this box powers on, turn the TV on and switch it to HDMI 3", which removes the other half of the reason I used to need two remotes.
Samsung, straight from the phone
The Samsung is a TV at another house, so the home server can't reach it. The phone talks to it directly on whatever network it's on, which raised two problems.
The TV serves a self-signed certificate on 8002. Rather than disabling validation, the app trusts it on first use for that host and pins the leaf's SHA-256. If it ever changes, the connection is refused:
let der = SecCertificateCopyData(leaf) as Data
let hash = SHA256.hash(data: der).map { String(format: "%02x", $0) }.joined()
if let pinned = config.certSHA256, pinned != hash {
completionHandler(.cancelAuthenticationChallenge, nil)
return
}
Discovery is normally SSDP, which on iOS means multicast, which means applying for Apple's multicast networking entitlement. Instead, the app sweeps the phone's /24 for Samsung's plain HTTP info endpoint on port 8001, 48 hosts at a time with a 1.2 s timeout:
let hosts = (1...254).map { "\(prefix).\($0)" }.filter { $0 != ip }
for chunk in stride(from: 0, to: hosts.count, by: 48).map({ Array(hosts[$0..<min($0 + 48, hosts.count)]) }) {
await withTaskGroup(of: Found?.self) { g in
for h in chunk { g.addTask { await probe(h) } }
for await f in g { if let f { found.append(f) } }
}
}
It finishes in a few seconds and only needs the ordinary local network permission prompt.
A token that can only press buttons
The backend that proxies the daemon does a lot more than TVs. I didn't want a remote app, and especially its widgets and Siri intents, holding a session that can do everything. So there's a separate remote-only bearer token, honoured on the remote routes and nowhere else, compared in constant time:
if auth.lower().startswith("bearer "):
tok = _remote_token()
if tok and hmac.compare_digest(auth[7:].strip(), tok):
return
require_auth(request)
Lose the phone, and the worst someone can do is change the channel.
Control Center and Siri
iOS 18 lets apps put buttons in Control Center and on the Lock Screen. A ControlWidget backed by a configurable AppIntent means one control type covers every combination — you pick a TV and a button when you add it, and add as many as you want:
struct TVButtonConfiguration: ControlConfigurationIntent {
static let title: LocalizedStringResource = "TV Button"
@Parameter(title: "TV") var tv: TVEntity?
@Parameter(title: "Button", default: .playpause) var button: TVKey
}
The same intents — press a button, switch input, launch an app — are exposed to Siri and Shortcuts, so pausing a TV doesn't need the app open at all.
What I'd do differently
Start with the warm connections. I built the per-press version first because it was simpler, measured it, and threw it away; the persistent-connection design isn't really more code, it just has to handle the link going stale. And I'd have checked pyatv's listener semantics before spending time wondering why my reconnect logic never ran.