SmartFox: launcher, Siri Remote driver, Debian image and installer

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Tamas Csikel
2026-10-24 09:06:06 +02:00
commit 79b03cac95
91 changed files with 15874 additions and 0 deletions

View File

@@ -0,0 +1,32 @@
#!/usr/bin/env bash
# Scans for an Apple BLE HID device (Siri Remote in pairing mode) and pairs,
# trusts and connects it as soon as it shows up.
# usage: autopair.sh [seconds]
LIMIT="${1:-180}"
strip() { sed 's/\x1b\[[0-9;]*m//g'; }
bluetoothctl pairable on >/dev/null
# Background scan for the whole window.
timeout "$LIMIT" bluetoothctl --timeout "$LIMIT" scan le >/dev/null 2>&1 &
SCAN=$!
trap 'kill $SCAN 2>/dev/null' EXIT
end=$((SECONDS + LIMIT))
while [ $SECONDS -lt $end ]; do
for m in $(bluetoothctl devices | strip | awk '{print $2}'); do
info=$(bluetoothctl info "$m" | strip)
if grep -q "00001812" <<<"$info" && grep -q "Key: 0x004c" <<<"$info" && grep -q "Paired: no" <<<"$info"; then
echo "found Apple HID $m, pairing..."
kill $SCAN 2>/dev/null
{ echo "agent NoInputNoOutput"; echo "default-agent"; sleep 1
echo "pair $m"; sleep 15; echo "trust $m"; sleep 1
echo "connect $m"; sleep 6; echo quit; } | bluetoothctl 2>&1 | strip \
| grep -E "Pairing|Paired|Bonded|trust|Connected|Failed|Error|ServicesResolved" | sort -u
bluetoothctl info "$m" | strip | grep -E "Name|Alias|Paired|Bonded|Trusted|Connected|Modalias"
exit 0
fi
done
sleep 1
done
echo "TIMEOUT: no Apple HID device in pairing mode"
exit 1

View File

@@ -0,0 +1,158 @@
#!/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()

View File

@@ -0,0 +1,33 @@
#!/usr/bin/env python3
"""Extracts ATT notifications from `btmon -r capture.btsnoop` text output.
usage: btmon -r cap.btsnoop | notifs.py [handle ...]
Prints: time handle hexdata
"""
import re
import sys
want = set(sys.argv[1:])
ts = 0.0
lines = sys.stdin.read().split("\n")
i = 0
while i < len(lines):
l = lines[i]
m = re.search(r"LE-ACL:.*\]\s+(\d+\.\d+)\s*$", l)
if m:
ts = float(m.group(1))
if "Handle Value Notification" in l:
h = re.search(r"Handle: (0x[0-9a-f]+)", lines[i + 1]).group(1)
data = []
j = i + 3
while j < len(lines):
m2 = re.match(r"^\s{8}((?:[0-9a-f]{2} )+)", lines[j] + " ")
if not m2:
break
data += m2.group(1).split()
j += 1
if not want or h in want:
print(f"{ts:9.3f} {h} {' '.join(data)}")
i = j
continue
i += 1

View File

@@ -0,0 +1,89 @@
#!/usr/bin/env python3
"""Siri Remote probe: lists Apple HID devices, dumps report descriptors and
streams raw hidraw reports (hex, with changed bytes marked).
usage:
probe.py list # devices + descriptors
probe.py watch [hidrawN] [-o log.txt]
"""
import glob
import os
import select
import sys
import time
APPLE = "0000004C"
def devices():
out = []
for path in sorted(glob.glob("/sys/class/hidraw/hidraw*")):
dev = os.path.realpath(os.path.join(path, "device"))
uevent = open(os.path.join(dev, "uevent")).read()
info = dict(l.split("=", 1) for l in uevent.split() if "=" in l)
hid_id = info.get("HID_ID", "") # bus:vendor:product
desc = open(os.path.join(dev, "report_descriptor"), "rb").read()
out.append({
"node": "/dev/" + os.path.basename(path),
"name": info.get("HID_NAME", "?"),
"id": hid_id,
"driver": info.get("DRIVER", "?"),
"apple": APPLE in hid_id.upper(),
"desc": desc,
})
return out
def cmd_list():
for d in devices():
mark = " <-- Apple" if d["apple"] else ""
print(f'{d["node"]} {d["name"]} id={d["id"]} driver={d["driver"]}{mark}')
if d["apple"]:
print(" report descriptor (%d bytes):" % len(d["desc"]))
h = d["desc"].hex(" ")
for i in range(0, len(h), 96):
print(" ", h[i:i + 96])
def cmd_watch(args):
log = None
if "-o" in args:
i = args.index("-o")
log = open(args[i + 1], "a")
args = args[:i] + args[i + 2:]
nodes = args or [d["node"] for d in devices() if d["apple"]]
if not nodes:
sys.exit("no Apple hidraw device found (is the remote paired and connected?)")
fds = {os.open(n, os.O_RDONLY | os.O_NONBLOCK): n for n in nodes}
last = {}
print("watching", ", ".join(nodes), "- Ctrl+C to stop", flush=True)
t0 = time.monotonic()
while True:
r, _, _ = select.select(list(fds), [], [])
for fd in r:
try:
data = os.read(fd, 256)
except BlockingIOError:
continue
key = (fd, data[0] if data else None)
prev = last.get(key)
last[key] = data
cells = []
for i, b in enumerate(data):
changed = prev is not None and (i >= len(prev) or prev[i] != b)
cells.append(("*" if changed else " ") + f"{b:02x}")
line = f"{time.monotonic() - t0:9.3f} {fds[fd]} len={len(data):3d} |{''.join(cells)}"
print(line, flush=True)
if log:
log.write(line + "\n")
log.flush()
if __name__ == "__main__":
a = sys.argv[1:]
if not a or a[0] == "list":
cmd_list()
elif a[0] == "watch":
cmd_watch(a[1:])
else:
print(__doc__)

View File

@@ -0,0 +1,25 @@
#!/usr/bin/env bash
# Second root step: let sf-remote own the Siri Remote's HID service.
# BlueZ's HID (HoG) plugin drops the remote's vendor reports, so we disable it
# and sf-remote reads the GATT characteristics itself over D-Bus.
# Run: sudo bash setup-host-2.sh
set -euo pipefail
if command -v dnf >/dev/null; then
dnf install -y dbus-devel pkgconf-pkg-config
elif command -v apt-get >/dev/null; then
apt-get install -y libdbus-1-dev pkg-config
fi
BTD=$(systemctl cat bluetooth | sed -n 's/^ExecStart=\(\/[^ ]*bluetoothd\).*/\1/p' | head -1)
mkdir -p /etc/systemd/system/bluetooth.service.d
cat >/etc/systemd/system/bluetooth.service.d/smartfox.conf <<EOF
[Service]
ExecStart=
ExecStart=$BTD --noplugin=input,hog
EOF
systemctl daemon-reload
systemctl restart bluetooth
sleep 2
systemctl --no-pager status bluetooth | head -5
echo "== done (undo: rm /etc/systemd/system/bluetooth.service.d/smartfox.conf && systemctl daemon-reload && systemctl restart bluetooth)"

View File

@@ -0,0 +1,39 @@
#!/usr/bin/env bash
# One-time root setup for the Siri Remote test host (Fedora/Debian).
# Run: sudo bash setup-host.sh <user>
set -euo pipefail
USER_NAME="${1:-${SUDO_USER:-}}"
[ -n "$USER_NAME" ] || { echo "usage: sudo bash $0 <user>"; exit 1; }
echo "== packages"
if command -v dnf >/dev/null; then
dnf install -y evtest hid-tools bluez bluez-tools || dnf install -y evtest bluez
elif command -v apt-get >/dev/null; then
apt-get install -y evtest bluez python3-hid-tools || apt-get install -y evtest bluez
fi
echo "== unblock bluetooth (persistent)"
rfkill unblock bluetooth
systemctl enable --now bluetooth
# Keep the adapter on after reboot.
sed -i 's/^#\?AutoEnable=.*/AutoEnable=true/' /etc/bluetooth/main.conf || true
echo "== device access for group 'smartfox'"
groupadd -f smartfox
usermod -aG smartfox,input "$USER_NAME"
cat >/etc/udev/rules.d/70-smartfox.rules <<'EOF'
# SmartFox: remote daemon reads raw HID and writes virtual key events.
KERNEL=="hidraw*", SUBSYSTEM=="hidraw", GROUP="smartfox", MODE="0660"
KERNEL=="uinput", SUBSYSTEM=="misc", GROUP="smartfox", MODE="0660", OPTIONS+="static_node=uinput"
EOF
modprobe uinput || true
udevadm control --reload-rules
udevadm trigger --subsystem-match=hidraw --subsystem-match=misc
# Read-only debugging without a password: btmon capture.
cat >/etc/sudoers.d/smartfox-btmon <<EOF
$USER_NAME ALL=(root) NOPASSWD: /usr/bin/btmon
EOF
chmod 440 /etc/sudoers.d/smartfox-btmon
echo "== done. Log out and back in (or reconnect ssh) for the new groups."