Files
os/tools/siri-remote/fastpair.py
2026-10-24 09:06:06 +02:00

159 lines
5.3 KiB
Python

#!/usr/bin/env python3
"""Event-driven Siri Remote pairing over BlueZ D-Bus.
The remote only advertises for a fraction of a second at a time in pairing
mode, so we react to the very first advertisement (InterfacesAdded /
PropertiesChanged) and call Pair() immediately.
usage: fastpair.py [timeout_seconds]
"""
import sys
import time
import dbus
import dbus.mainloop.glib
import dbus.service
from gi.repository import GLib
BUS = "org.bluez"
AGENT_PATH = "/smartfox/agent"
APPLE = 0x004C
HID_UUID = "00001812-0000-1000-8000-00805f9b34fb"
dbus.mainloop.glib.DBusGMainLoop(set_as_default=True)
bus = dbus.SystemBus()
loop = GLib.MainLoop()
t0 = time.monotonic()
busy = set()
done = {"ok": False}
def log(*a):
print(f"{time.monotonic() - t0:7.3f}", *a, flush=True)
class Agent(dbus.service.Object):
"""NoInputNoOutput agent: accept everything (just works pairing)."""
@dbus.service.method("org.bluez.Agent1", in_signature="", out_signature="")
def Release(self):
pass
@dbus.service.method("org.bluez.Agent1", in_signature="os", out_signature="")
def AuthorizeService(self, device, uuid):
log("authorize service", uuid)
@dbus.service.method("org.bluez.Agent1", in_signature="o", out_signature="")
def RequestAuthorization(self, device):
log("authorize pairing")
@dbus.service.method("org.bluez.Agent1", in_signature="ou", out_signature="")
def RequestConfirmation(self, device, passkey):
log("confirm passkey", passkey)
@dbus.service.method("org.bluez.Agent1", in_signature="", out_signature="")
def Cancel(self):
log("agent cancel")
def adapter_path():
om = dbus.Interface(bus.get_object(BUS, "/"), "org.freedesktop.DBus.ObjectManager")
for path, ifaces in om.GetManagedObjects().items():
if "org.bluez.Adapter1" in ifaces:
return path
sys.exit("no adapter")
def is_remote(props):
md = props.get("ManufacturerData", {})
uuids = [str(u).lower() for u in props.get("UUIDs", [])]
appearance = int(props.get("Appearance", 0))
return APPLE in [int(k) for k in md.keys()] and (HID_UUID in uuids or appearance == 0x03C0)
def pair(path):
if path in busy or done["ok"]:
return
busy.add(path)
dev = bus.get_object(BUS, path)
props = dbus.Interface(dev, "org.freedesktop.DBus.Properties")
addr = props.Get("org.bluez.Device1", "Address")
if props.Get("org.bluez.Device1", "Paired"):
log("already paired", addr)
return
log("remote seen", addr, "-> Pair()")
def ok():
log("PAIRED", addr)
props.Set("org.bluez.Device1", "Trusted", True)
done["ok"] = True
try:
dbus.Interface(dev, "org.bluez.Device1").Connect(timeout=20)
except dbus.DBusException as e:
log("connect:", e.get_dbus_name()) # usually already connected after pairing
for k in ("Name", "Alias", "Modalias", "Connected", "Bonded", "UUIDs"):
try:
log(f" {k}:", props.Get("org.bluez.Device1", k))
except dbus.DBusException:
pass
GLib.timeout_add(1500, loop.quit)
def err(e):
log("pair failed", addr, e.get_dbus_name(), e.get_dbus_message())
busy.discard(path)
dbus.Interface(dev, "org.bluez.Device1").Pair(reply_handler=ok, error_handler=err, timeout=30)
def on_added(path, ifaces):
p = ifaces.get("org.bluez.Device1")
if p and is_remote(p):
pair(path)
def on_changed(iface, changed, invalidated, path=None):
if iface != "org.bluez.Device1" or not ("ManufacturerData" in changed or "RSSI" in changed):
return
props = dbus.Interface(bus.get_object(BUS, path), "org.freedesktop.DBus.Properties").GetAll("org.bluez.Device1")
if is_remote(props):
pair(path)
def main():
limit = int(sys.argv[1]) if len(sys.argv) > 1 else 180
Agent(bus, AGENT_PATH)
mgr = dbus.Interface(bus.get_object(BUS, "/org/bluez"), "org.bluez.AgentManager1")
mgr.RegisterAgent(AGENT_PATH, "NoInputNoOutput")
mgr.RequestDefaultAgent(AGENT_PATH)
ad_path = adapter_path()
ad = dbus.Interface(bus.get_object(BUS, ad_path), "org.bluez.Adapter1")
adp = dbus.Interface(bus.get_object(BUS, ad_path), "org.freedesktop.DBus.Properties")
adp.Set("org.bluez.Adapter1", "Pairable", True)
bus.add_signal_receiver(on_added, "InterfacesAdded", "org.freedesktop.DBus.ObjectManager", BUS)
bus.add_signal_receiver(on_changed, "PropertiesChanged", "org.freedesktop.DBus.Properties", BUS,
path_keyword="path")
# Devices already known from earlier scans (stale, unpaired) get removed so we see fresh adverts.
om = dbus.Interface(bus.get_object(BUS, "/"), "org.freedesktop.DBus.ObjectManager")
for path, ifaces in om.GetManagedObjects().items():
d = ifaces.get("org.bluez.Device1")
if d and is_remote(d) and not d.get("Paired"):
ad.RemoveDevice(path)
ad.SetDiscoveryFilter({"Transport": "le", "DuplicateData": True})
ad.StartDiscovery()
log(f"scanning for {limit}s - hold Back + Volume Up on the remote now")
GLib.timeout_add_seconds(limit, loop.quit)
loop.run()
try:
ad.StopDiscovery()
except dbus.DBusException:
pass
print("RESULT:", "paired" if done["ok"] else "not paired", flush=True)
if __name__ == "__main__":
main()