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,85 @@
//! Global hotkeys from physical keyboards. Apps (Chromium) own keyboard focus,
//! so the launcher can't see these; we read evdev directly (without grabbing).
//! F12 -> home
//! Esc held 0.8 s -> home (a short press still means "back" in the app)
use std::collections::HashSet;
use std::path::PathBuf;
use std::sync::{Arc, Mutex};
use std::time::Duration;
use evdev::{EventType, KeyCode};
use crate::link::Link;
const ESC_HOLD: Duration = Duration::from_millis(800);
const OWN_DEVICE: &str = "SmartFox Siri Remote";
pub fn spawn(link: Link) {
std::thread::spawn(move || {
let rt = match tokio::runtime::Builder::new_current_thread().enable_all().build() {
Ok(rt) => rt,
Err(e) => return log::error!("keyboard watcher: {e}"),
};
rt.block_on(watch(link));
});
}
async fn watch(link: Link) {
let watched: Arc<Mutex<HashSet<PathBuf>>> = Arc::default();
let mut rescan = tokio::time::interval(Duration::from_secs(3));
loop {
rescan.tick().await;
link.resend();
for (path, dev) in evdev::enumerate() {
if watched.lock().unwrap().contains(&path) || dev.name() == Some(OWN_DEVICE) {
continue;
}
let is_keyboard = dev
.supported_keys()
.is_some_and(|k| k.contains(KeyCode::KEY_ESC) && k.contains(KeyCode::KEY_F12));
if !is_keyboard {
continue;
}
let Ok(mut stream) = dev.into_event_stream() else { continue };
log::info!("watching keyboard {}", path.display());
watched.lock().unwrap().insert(path.clone());
let (link, watched) = (link.clone(), watched.clone());
tokio::spawn(async move {
// Deadline at which a still-held Esc turns into "home".
let mut esc_deadline: Option<tokio::time::Instant> = None;
loop {
let ev = match esc_deadline {
Some(deadline) => tokio::select! {
ev = stream.next_event() => ev,
_ = tokio::time::sleep_until(deadline) => {
log::info!("Esc held -> home");
esc_deadline = None;
link.home();
continue;
}
},
None => stream.next_event().await,
};
let Ok(ev) = ev else { break };
if ev.event_type() != EventType::KEY {
continue;
}
let (code, value) = (KeyCode::new(ev.code()), ev.value());
if code == KeyCode::KEY_F12 && value == 1 {
log::info!("F12 -> home");
link.home();
} else if code == KeyCode::KEY_ESC {
match value {
1 => esc_deadline = Some(tokio::time::Instant::now() + ESC_HOLD),
0 => esc_deadline = None,
_ => {}
}
}
}
log::info!("keyboard {} gone", path.display());
watched.lock().unwrap().remove(&path);
});
}
}
}

View File

@@ -0,0 +1,160 @@
//! Connection to the launcher's command socket: global `home`, remote status
//! and standby. The launcher answers every command with its standby state
//! (`standby off|screen|suspend <n>`), which we cache here.
use std::io::{BufRead, BufReader, Write};
use std::os::unix::net::UnixStream;
use std::path::PathBuf;
use std::sync::{Arc, Mutex};
use std::time::Duration;
use tokio::sync::watch;
/// Remote states the launcher understands.
pub mod state {
/// No Bluetooth controller present.
pub const NO_ADAPTER: &str = "no-adapter";
/// No paired remote: scanning for one in pairing mode.
pub const SEARCHING: &str = "searching";
/// A remote in pairing mode was found; pairing in progress.
pub const PAIRING: &str = "pairing";
/// Paired but not connected (asleep).
pub const PAIRED: &str = "paired";
pub const CONNECTED: &str = "connected";
}
/// The launcher's standby state.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum Standby {
#[default]
Off,
/// Screen off, machine running.
Screen,
/// The launcher wants the machine suspended; the number changes with
/// every request (also when it asks again after a stray wake-up).
Suspend(u64),
}
impl Standby {
pub fn parse(line: &str) -> Option<Standby> {
let mut w = line.split_whitespace();
if w.next()? != "standby" {
return None;
}
match w.next()? {
"off" => Some(Standby::Off),
"screen" => Some(Standby::Screen),
"suspend" => Some(Standby::Suspend(w.next().and_then(|n| n.parse().ok()).unwrap_or(0))),
_ => None,
}
}
pub fn active(self) -> bool {
self != Standby::Off
}
}
#[derive(Clone)]
pub struct Link {
socket: Option<PathBuf>,
status: Arc<Mutex<String>>,
standby: Arc<watch::Sender<Standby>>,
}
impl Link {
pub fn new(socket: Option<PathBuf>) -> Self {
Self { socket, status: Arc::default(), standby: Arc::new(watch::Sender::new(Standby::Off)) }
}
/// Sends one command and reads the launcher's standby reply.
fn send(&self, line: &str) -> bool {
let Some(path) = &self.socket else { return false };
let result = UnixStream::connect(path).and_then(|mut s| {
s.set_read_timeout(Some(Duration::from_millis(500)))?;
s.write_all(format!("{line}\n").as_bytes())?;
let mut reply = String::new();
// An older launcher doesn't answer; the timeout covers that.
let _ = BufReader::new(&s).read_line(&mut reply);
Ok(reply)
});
match result {
Ok(reply) => {
if let Some(state) = Standby::parse(&reply) {
self.standby.send_if_modified(|cur| {
let changed = *cur != state;
if changed {
log::info!("standby: {state:?}");
*cur = state;
}
changed
});
}
true
}
Err(e) => {
log::trace!("launcher socket {}: {e}", path.display());
false
}
}
}
/// Asks the launcher to come to the front. False if it isn't listening.
pub fn home(&self) -> bool {
self.send("home")
}
/// Power button: the launcher toggles standby.
pub fn power(&self) -> Standby {
self.send("power");
self.standby()
}
/// Leave standby.
pub fn wake(&self) {
self.send("wake");
}
/// Last known standby state (refreshed with every command, at least every 3 s).
pub fn standby(&self) -> Standby {
*self.standby.borrow()
}
pub fn watch_standby(&self) -> watch::Receiver<Standby> {
self.standby.subscribe()
}
pub fn status(&self, s: &str) {
let changed = {
let mut cur = self.status.lock().unwrap();
let changed = *cur != s;
*cur = s.to_string();
changed
};
if changed {
log::info!("remote status: {s}");
}
self.send(&format!("remote {s}"));
}
/// Re-sends the last status (the launcher may have restarted).
pub fn resend(&self) {
let s = self.status.lock().unwrap().clone();
if !s.is_empty() {
self.send(&format!("remote {s}"));
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn parses_standby_reply() {
assert_eq!(Standby::parse("standby off\n"), Some(Standby::Off));
assert_eq!(Standby::parse("standby screen"), Some(Standby::Screen));
assert_eq!(Standby::parse("standby suspend 7"), Some(Standby::Suspend(7)));
assert_eq!(Standby::parse(""), None);
assert!(Standby::Screen.active() && !Standby::Off.active());
}
}

View File

@@ -0,0 +1,542 @@
use std::pin::Pin;
use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant};
use anyhow::{Context, Result};
use bluer::{Adapter, AddressType, Device, Uuid};
use evdev::uinput::VirtualDevice;
use evdev::{AttributeSet, EventType, InputEvent, KeyCode};
use futures::{Stream, StreamExt};
use crate::link::{Link, Standby, state};
use crate::protocol::{self, Gestures, Report, Swipe, button};
use crate::wake;
const APPLE: u32 = 0x004C;
/// Known Siri Remote product ids (0x0314/0x0315: 2nd/3rd gen aluminium).
const PRODUCTS: [u32; 3] = [0x0314, 0x0315, 0x0266];
const HID_SERVICE: u16 = 0x1812;
const HID_REPORT: u16 = 0x2A4D;
const REPEAT_DELAY: Duration = Duration::from_millis(450);
const REPEAT_EVERY: Duration = Duration::from_millis(110);
struct Options {
dry_run: bool,
step: i32,
/// Launcher command socket; the TV button sends `home` there instead of a key.
home_socket: Option<std::path::PathBuf>,
}
fn parse_args() -> Options {
let mut o = Options {
dry_run: false,
step: 300,
home_socket: std::env::var_os("SMARTFOX_SOCKET").map(Into::into),
};
let mut args = std::env::args().skip(1);
while let Some(a) = args.next() {
match a.as_str() {
"--dry-run" | "-n" => o.dry_run = true,
"--step" => o.step = args.next().and_then(|v| v.parse().ok()).unwrap_or(o.step),
"--home-socket" => o.home_socket = args.next().map(Into::into),
other => log::warn!("unknown argument {other}"),
}
}
o
}
fn key_for(bit: u16) -> Option<KeyCode> {
Some(match bit {
button::UP => KeyCode::KEY_UP,
button::DOWN => KeyCode::KEY_DOWN,
button::LEFT => KeyCode::KEY_LEFT,
button::RIGHT => KeyCode::KEY_RIGHT,
button::SELECT => KeyCode::KEY_ENTER,
button::BACK => KeyCode::KEY_ESC,
button::HOME => KeyCode::KEY_HOMEPAGE,
button::PLAY_PAUSE => KeyCode::KEY_PLAYPAUSE,
button::VOL_UP => KeyCode::KEY_VOLUMEUP,
button::VOL_DOWN => KeyCode::KEY_VOLUMEDOWN,
button::MUTE => KeyCode::KEY_MUTE,
button::SIRI => KeyCode::KEY_VOICECOMMAND,
// Not KEY_POWER: logind would shut the machine down. The launcher
// handles standby (`power` on its socket), see serve().
button::POWER => return None,
_ => return None,
})
}
fn repeats(bit: u16) -> bool {
matches!(
bit,
button::UP
| button::DOWN
| button::LEFT
| button::RIGHT
| button::VOL_UP
| button::VOL_DOWN
)
}
/// Virtual keyboard (or a logger in --dry-run mode).
struct Keys {
dev: Option<VirtualDevice>,
}
impl Keys {
fn new(dry_run: bool) -> Result<Self> {
if dry_run {
return Ok(Self { dev: None });
}
let mut keys = AttributeSet::<KeyCode>::new();
for (bit, _) in button::ALL {
if let Some(k) = key_for(bit) {
keys.insert(k);
}
}
// Sent when going into standby: pauses playback in the app.
keys.insert(KeyCode::KEY_PAUSECD);
let dev = VirtualDevice::builder()
.context("opening /dev/uinput (is the user in the smartfox group?)")?
.name("SmartFox Siri Remote")
.with_keys(&keys)?
.build()?;
Ok(Self { dev: Some(dev) })
}
fn send(&mut self, key: KeyCode, value: i32) {
log::debug!("key {key:?} {}", ["up", "down", "repeat"][value as usize]);
if let Some(dev) = self.dev.as_mut() {
let ev = InputEvent::new(EventType::KEY.0, key.code(), value);
if let Err(e) = dev.emit(&[ev]) {
log::warn!("uinput: {e}");
}
}
}
fn tap(&mut self, key: KeyCode) {
self.send(key, 1);
self.send(key, 0);
}
}
fn short_uuid(u: Uuid) -> Option<u16> {
let s = u.to_string();
s.ends_with("-0000-1000-8000-00805f9b34fb")
.then(|| u16::from_str_radix(&s[4..8], 16).ok())
.flatten()
}
async fn find_remote(adapter: &Adapter) -> Result<Option<Device>> {
for addr in adapter.device_addresses().await? {
let dev = adapter.device(addr)?;
let Ok(Some(m)) = dev.modalias().await else {
continue;
};
if m.vendor == APPLE
&& PRODUCTS.contains(&m.product)
&& dev.is_paired().await.unwrap_or(false)
{
return Ok(Some(dev));
}
}
Ok(None)
}
type Notify = Pin<Box<dyn Stream<Item = Vec<u8>> + Send>>;
async fn subscribe(dev: &Device) -> Result<Vec<Notify>> {
let mut streams: Vec<Notify> = Vec::new();
for svc in dev.services().await? {
if short_uuid(svc.uuid().await?) != Some(HID_SERVICE) {
continue;
}
for ch in svc.characteristics().await? {
if short_uuid(ch.uuid().await?) != Some(HID_REPORT) || !ch.flags().await?.notify {
continue;
}
log::info!("subscribing to report characteristic {:#06x}", ch.id());
streams.push(Box::pin(ch.notify().await?));
}
}
if streams.is_empty() {
anyhow::bail!("no HID report characteristics visible - is BlueZ's input plugin disabled?");
}
Ok(streams)
}
/// Power toggles standby; in standby any other button just wakes the TV.
fn standby_button(bit: u16, link: &Link, keys: &mut Keys) {
let before = link.standby();
if bit != button::POWER {
log::info!("button in standby -> wake");
link.wake();
return;
}
let after = link.power();
log::info!("power: {before:?} -> {after:?}");
if !before.active() && after.active() {
keys.tap(KeyCode::KEY_PAUSECD);
}
}
/// Puts the machine to sleep whenever the launcher asks for it (a new
/// `standby suspend <n>`). The launcher runs as `tv` and can't do this.
async fn suspend_on_request(link: Link, target: Arc<Mutex<Option<wake::Target>>>) {
let mut rx = link.watch_standby();
let mut done = None;
loop {
let Standby::Suspend(n) = *rx.borrow_and_update() else {
if rx.changed().await.is_err() {
return;
}
continue;
};
if done == Some(n) {
if rx.changed().await.is_err() {
return;
}
continue;
}
done = Some(n);
// Give the screen time to go dark and the app to pause.
tokio::time::sleep(Duration::from_millis(1500)).await;
if link.standby() != Standby::Suspend(n) {
log::info!("suspend {n} cancelled");
continue;
}
let target = *target.lock().unwrap();
let result = tokio::task::spawn_blocking(move || suspend(target)).await;
if let Ok(Err(e)) | Err(e) = result.map_err(anyhow::Error::from) {
log::warn!("suspend: {e:#}");
}
}
}
fn suspend(target: Option<wake::Target>) -> Result<()> {
let n = wake::enable_controller_wakeup();
log::info!("wake: controller wakeup ready ({n} switched on)");
match target {
Some(t) => match wake::allow_remote_wakeup(&t) {
Ok(()) => log::info!("wake: remote may wake the machine"),
Err(e) => log::warn!("wake: {e:#} (only the PC's own button will wake it)"),
},
None => log::warn!("wake: no paired remote known"),
}
log::info!("suspending");
let status = std::process::Command::new("systemctl").arg("suspend").status().context("systemctl suspend")?;
if !status.success() {
anyhow::bail!("systemctl suspend: {status}");
}
Ok(())
}
async fn wake_target(adapter: &Adapter, dev: &Device) -> Option<wake::Target> {
let index = adapter.name().strip_prefix("hci")?.parse().ok()?;
let public = match dev.address_type().await.ok()? {
AddressType::LePublic => true,
AddressType::LeRandom => false,
AddressType::BrEdr => return None,
};
Some(wake::Target { index, addr: dev.address().0, public })
}
/// Handles one connection until the remote disconnects.
async fn serve(dev: &Device, keys: &mut Keys, step: i32, link: &Link) -> Result<()> {
let mut reports = futures::stream::select_all(subscribe(dev).await?);
let mut gestures = Gestures::new(step);
let mut held: u16 = 0;
// Buttons whose press woke (or put to sleep) the TV: their release and
// auto-repeat must not reach the app.
let mut swallowed: u16 = 0;
let mut held_since = Instant::now();
let mut last_repeat = Instant::now();
let mut tick = tokio::time::interval(Duration::from_millis(20));
loop {
tokio::select! {
item = reports.next() => {
let Some(data) = item else { return Ok(()) };
match protocol::parse(&data) {
Report::Buttons(state) => {
let changed = state ^ held;
for (bit, name) in button::ALL {
if changed & bit == 0 { continue; }
let down = state & bit != 0;
log::info!("{name} {}", if down { "pressed" } else { "released" });
if !down && swallowed & bit != 0 {
swallowed &= !bit;
continue;
}
if down && (bit == button::POWER || link.standby().active()) {
swallowed |= bit;
standby_button(bit, link, keys);
continue;
}
if bit == button::HOME && down && link.home() {
continue;
}
if let Some(k) = key_for(bit) { keys.send(k, down as i32); }
}
if state & !held != 0 {
gestures.on_button();
held_since = Instant::now();
}
held = state;
}
Report::Touch(f) => {
log::trace!("touch {:5} {:5} size {:?}{}", f.x, f.y, f.size, if f.released { " released" } else { "" });
if let Some(s) = gestures.on_touch(&f) {
log::info!("swipe {s:?}");
if link.standby().active() {
continue; // a swipe doesn't wake the TV
}
keys.tap(match s {
Swipe::Up => KeyCode::KEY_UP,
Swipe::Down => KeyCode::KEY_DOWN,
Swipe::Left => KeyCode::KEY_LEFT,
Swipe::Right => KeyCode::KEY_RIGHT,
});
}
}
Report::Audio => log::trace!("siri audio packet"),
Report::Unknown(n) => log::debug!("unknown report ({n} bytes): {data:02x?}"),
}
}
_ = tick.tick() => {
// Auto-repeat for held d-pad and volume keys.
if held != 0 && held_since.elapsed() >= REPEAT_DELAY && last_repeat.elapsed() >= REPEAT_EVERY {
last_repeat = Instant::now();
for (bit, _) in button::ALL {
if held & !swallowed & bit != 0 && repeats(bit) {
if let Some(k) = key_for(bit) { keys.send(k, 2); }
}
}
}
}
}
}
}
/// The remote advertises with a rotating private address. The controller's
/// accept list only knows its identity address, so BlueZ's passive
/// auto-connect never sees it. An active scan lets the kernel resolve the
/// address with the bonded IRK; we connect as soon as an advert arrives.
async fn wait_for_advert(adapter: &Adapter, dev: &Device) -> Result<()> {
use bluer::{DeviceEvent, DeviceProperty, DiscoveryFilter, DiscoveryTransport};
adapter
.set_discovery_filter(DiscoveryFilter {
transport: DiscoveryTransport::Le,
duplicate_data: true,
..Default::default()
})
.await?;
let mut discovery = adapter.discover_devices_with_changes().await?;
let mut events = dev.events().await?;
let mut recheck = tokio::time::interval(Duration::from_secs(2));
loop {
tokio::select! {
// A connection may come up between our checks (e.g. a pending Connect()).
_ = recheck.tick() => {
if dev.is_connected().await.unwrap_or(false) {
return Ok(());
}
// Removed in the launcher's settings: go back to pairing.
if !dev.is_paired().await.unwrap_or(false) {
anyhow::bail!("remote {} was unpaired", dev.address());
}
}
ev = events.next() => match ev {
Some(DeviceEvent::PropertyChanged(DeviceProperty::Rssi(rssi))) => {
log::info!("remote advertising (rssi {rssi}), connecting");
return Ok(());
}
Some(DeviceEvent::PropertyChanged(DeviceProperty::Connected(true))) => return Ok(()),
Some(_) => {}
None => anyhow::bail!("device event stream ended"),
},
// Keep the discovery session alive and drained.
_ = discovery.next() => {}
}
}
}
fn is_remote_advert(md: Option<&std::collections::HashMap<u16, Vec<u8>>>, uuids: Option<&std::collections::HashSet<Uuid>>, appearance: Option<u16>) -> bool {
let apple = md.is_some_and(|m| m.contains_key(&(APPLE as u16)));
let hid = uuids.is_some_and(|u| u.iter().any(|u| short_uuid(*u) == Some(HID_SERVICE)));
apple && (hid || appearance == Some(0x03C0))
}
/// Pairing mode: scan until a Siri Remote in pairing mode (Back + Volume Up)
/// shows up and pair it at once. It only advertises for ~0.2 s at a time with a
/// fresh private address, so we react to the first advert.
async fn pair_new(adapter: &Adapter, link: &Link) -> Result<Device> {
use bluer::{AdapterEvent, DiscoveryFilter, DiscoveryTransport};
adapter.set_pairable(true).await?;
adapter
.set_discovery_filter(DiscoveryFilter {
transport: DiscoveryTransport::Le,
duplicate_data: true,
..Default::default()
})
.await?;
let mut events = adapter.discover_devices_with_changes().await?;
link.status(state::SEARCHING);
let mut resend = tokio::time::interval(Duration::from_secs(5));
loop {
let addr = tokio::select! {
ev = events.next() => match ev {
Some(AdapterEvent::DeviceAdded(addr)) => addr,
Some(_) => continue,
None => anyhow::bail!("discovery ended"),
},
_ = resend.tick() => {
// Another paired remote may have appeared meanwhile.
if let Some(dev) = find_remote(adapter).await? {
return Ok(dev);
}
continue;
}
};
let dev = adapter.device(addr)?;
if dev.is_paired().await.unwrap_or(false) {
continue;
}
let md = dev.manufacturer_data().await.ok().flatten();
let uuids = dev.uuids().await.ok().flatten();
let appearance = dev.appearance().await.ok().flatten();
if !is_remote_advert(md.as_ref(), uuids.as_ref(), appearance) {
continue;
}
log::info!("remote in pairing mode: {addr}, pairing");
link.status(state::PAIRING);
match tokio::time::timeout(Duration::from_secs(30), dev.pair()).await {
Ok(Ok(())) => {
dev.set_trusted(true).await?;
log::info!("paired {}", dev.address());
return Ok(dev);
}
Ok(Err(e)) => log::info!("pair attempt failed: {e} (will retry on next advert)"),
Err(_) => log::info!("pair attempt timed out"),
}
link.status(state::SEARCHING);
}
}
async fn connect(adapter: &Adapter, dev: &Device) -> Result<bool> {
if dev.is_connected().await.unwrap_or(false) {
return Ok(true);
}
wait_for_advert(adapter, dev).await?;
if dev.is_connected().await.unwrap_or(false) {
return Ok(true);
}
match tokio::time::timeout(Duration::from_secs(10), dev.connect()).await {
Ok(Ok(())) => Ok(true),
Ok(Err(e)) if e.kind == bluer::ErrorKind::InProgress => {
tokio::time::sleep(Duration::from_secs(2)).await;
Ok(false)
}
Ok(Err(e)) => {
log::debug!("connect: {e}");
Ok(false)
}
Err(_) => {
log::debug!("connect timed out");
Ok(false)
}
}
}
pub fn run() -> Result<()> {
let opts = parse_args();
let link = Link::new(opts.home_socket.clone());
crate::keyboard::spawn(link.clone());
let rt = tokio::runtime::Builder::new_current_thread().enable_all().build()?;
rt.block_on(async move {
let mut keys = Keys::new(opts.dry_run)?;
let target: Arc<Mutex<Option<wake::Target>>> = Arc::default();
tokio::spawn(suspend_on_request(link.clone(), target.clone()));
let session = bluer::Session::new().await?;
// NoInputNoOutput agent that accepts "just works" pairing (registered once bluetoothd is up).
let mut agent = None;
loop {
// Without a controller bluetoothd isn't even running and D-Bus calls just hang.
let has_controller = std::fs::read_dir("/sys/class/bluetooth").is_ok_and(|mut d| d.next().is_some());
let adapter = if has_controller {
tokio::time::timeout(Duration::from_secs(5), session.default_adapter()).await.ok()
} else {
None
};
let adapter = match adapter {
Some(Ok(a)) if a.set_powered(true).await.is_ok() => a,
_ => {
link.status(state::NO_ADAPTER);
tokio::time::sleep(Duration::from_secs(3)).await;
continue;
}
};
if agent.is_none() {
agent = session
.register_agent(bluer::agent::Agent { request_default: true, ..Default::default() })
.await
.ok();
}
let dev = match find_remote(&adapter).await {
Ok(Some(dev)) => dev,
Ok(None) => match pair_new(&adapter, &link).await {
Ok(dev) => dev,
Err(e) => {
log::warn!("pairing: {e:#}");
tokio::time::sleep(Duration::from_secs(2)).await;
continue;
}
},
Err(e) => {
log::warn!("{e:#}");
tokio::time::sleep(Duration::from_secs(2)).await;
continue;
}
};
if !dev.is_connected().await.unwrap_or(false) {
link.status(state::PAIRED);
log::info!("waiting for {} (press any button)", dev.address());
match connect(&adapter, &dev).await {
Ok(true) => {}
Ok(false) => continue,
Err(e) => {
log::warn!("scan: {e:#}");
tokio::time::sleep(Duration::from_secs(2)).await;
continue;
}
}
}
let battery = dev.battery_percentage().await.ok().flatten();
log::info!("connected to {} (battery {:?}%)", dev.address(), battery);
link.status(state::CONNECTED);
// The remote only reconnects when a button is pressed, and that
// press is lost while connecting: after a suspend (or the remote's
// own sleep) the reconnect itself means "wake up".
if link.standby().active() {
log::info!("remote reconnected in standby -> wake");
link.wake();
}
if let Some(t) = wake_target(&adapter, &dev).await {
*target.lock().unwrap() = Some(t);
}
match serve(&dev, &mut keys, opts.step, &link).await {
Ok(()) => log::info!("remote disconnected"),
Err(e) => {
log::warn!("{e:#}");
tokio::time::sleep(Duration::from_secs(2)).await;
}
}
link.status(state::PAIRED);
}
})
}

View File

@@ -0,0 +1,30 @@
#![cfg_attr(not(target_os = "linux"), allow(dead_code))]
//! sf-remote: Apple Siri Remote driver for SmartFox.
//!
//! Subscribes to the remote's HID report characteristics over BlueZ D-Bus
//! (BlueZ's own HID plugin must be disabled, it drops these reports) and
//! turns buttons and touchpad swipes into key presses on a uinput device.
mod protocol;
#[cfg(target_os = "linux")]
mod keyboard;
#[cfg(target_os = "linux")]
mod link;
#[cfg(target_os = "linux")]
mod linux;
#[cfg(target_os = "linux")]
mod wake;
fn main() -> anyhow::Result<()> {
env_logger::Builder::from_env(env_logger::Env::default().default_filter_or("info")).init();
#[cfg(target_os = "linux")]
{
linux::run()
}
#[cfg(not(target_os = "linux"))]
{
anyhow::bail!("sf-remote needs Linux (BlueZ + uinput)")
}
}

View File

@@ -0,0 +1,200 @@
//! Siri Remote (2nd gen, Apple 0x004C:0x0315) wire format, reverse engineered
//! from btmon captures (see docs/siri-remote.md).
//!
//! All data arrives as HID Report (0x2A4D) GATT notifications, told apart by length:
//! - 2 bytes: button bitmask (u16 little-endian)
//! - 11 bytes: touchpad frame (~66 Hz while touched)
//! - 99 bytes: Siri microphone audio (not decoded)
/// Button bits (u16 little-endian of the 2-byte report).
pub mod button {
pub const HOME: u16 = 0x0001; // TV / Home
pub const VOL_UP: u16 = 0x0002;
pub const VOL_DOWN: u16 = 0x0004;
pub const SELECT: u16 = 0x0008; // center click
pub const POWER: u16 = 0x0010;
pub const SIRI: u16 = 0x0020;
pub const BACK: u16 = 0x0040;
pub const MUTE: u16 = 0x0080;
pub const PLAY_PAUSE: u16 = 0x0100;
pub const UP: u16 = 0x0200;
pub const RIGHT: u16 = 0x0400;
pub const DOWN: u16 = 0x0800;
pub const LEFT: u16 = 0x1000;
pub const ALL: [(u16, &str); 13] = [
(HOME, "home"),
(VOL_UP, "vol_up"),
(VOL_DOWN, "vol_down"),
(SELECT, "select"),
(POWER, "power"),
(SIRI, "siri"),
(BACK, "back"),
(MUTE, "mute"),
(PLAY_PAUSE, "play_pause"),
(UP, "up"),
(RIGHT, "right"),
(DOWN, "down"),
(LEFT, "left"),
];
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Report {
Buttons(u16),
Touch(TouchFrame),
Audio,
Unknown(usize),
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct TouchFrame {
/// Device timestamp (wraps), roughly 0.47 ms per unit.
pub stamp: u16,
/// Signed coordinates: +x right, +y up. Roughly -1100..+400 / -1100..+250.
pub x: i16,
pub y: i16,
/// Contact size / pressure-like values.
pub size: [u8; 3],
/// Last frame of a touch (finger lifted).
pub released: bool,
}
fn s12(v: u16) -> i16 {
if v >= 2048 { v as i16 - 4096 } else { v as i16 }
}
pub fn parse(data: &[u8]) -> Report {
match data.len() {
2 => Report::Buttons(u16::from_le_bytes([data[0], data[1]])),
11 => {
let x = s12(data[4] as u16 | ((data[5] as u16 & 0x0f) << 8));
let y = s12((data[5] as u16 >> 4) | ((data[6] as u16) << 4));
let size = [data[7], data[8], data[9]];
Report::Touch(TouchFrame {
stamp: u16::from_le_bytes([data[1], data[2]]),
x,
y,
size,
released: size == [0, 0, 0],
})
}
99 => Report::Audio,
n => Report::Unknown(n),
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Swipe {
Up,
Down,
Left,
Right,
}
/// Turns touch movement into discrete steps, like tvOS: every `step` units of
/// travel along the dominant axis emits one swipe. Touches that end in a
/// button click (ring/center press) are ignored.
pub struct Gestures {
pub step: i32,
origin: Option<(i32, i32)>,
suppressed: bool,
}
impl Default for Gestures {
fn default() -> Self {
Self { step: 300, origin: None, suppressed: false }
}
}
impl Gestures {
pub fn new(step: i32) -> Self {
Self { step, ..Default::default() }
}
/// A button press during a touch means the user is clicking, not swiping.
pub fn on_button(&mut self) {
if self.origin.is_some() {
self.suppressed = true;
}
}
pub fn on_touch(&mut self, f: &TouchFrame) -> Option<Swipe> {
if f.released {
self.origin = None;
self.suppressed = false;
return None;
}
let p = (f.x as i32, f.y as i32);
let Some(o) = self.origin else {
self.origin = Some(p);
return None;
};
if self.suppressed {
return None;
}
let (dx, dy) = (p.0 - o.0, p.1 - o.1);
let swipe = if dx.abs() >= self.step && dx.abs() * 2 > dy.abs() * 3 {
Some(if dx > 0 { Swipe::Right } else { Swipe::Left })
} else if dy.abs() >= self.step && dy.abs() * 2 > dx.abs() * 3 {
Some(if dy > 0 { Swipe::Up } else { Swipe::Down })
} else {
None
};
if swipe.is_some() {
self.origin = Some(p);
}
swipe
}
}
#[cfg(test)]
mod tests {
use super::*;
fn hex(s: &str) -> Vec<u8> {
s.split_whitespace().map(|b| u8::from_str_radix(b, 16).unwrap()).collect()
}
#[test]
fn buttons_from_capture() {
assert_eq!(parse(&hex("00 02")), Report::Buttons(button::UP));
assert_eq!(parse(&hex("08 00")), Report::Buttons(button::SELECT));
assert_eq!(parse(&hex("00 01")), Report::Buttons(button::PLAY_PAUSE));
assert_eq!(parse(&hex("40 00")), Report::Buttons(button::BACK));
assert_eq!(parse(&hex("00 00")), Report::Buttons(0));
}
#[test]
fn touch_from_capture() {
// Swipe left -> right crossing x = 0 (captured 448.406 / 448.452).
let Report::Touch(a) = parse(&hex("32 0c e9 00 ea 9f e8 83 6f 14 84")) else { panic!() };
let Report::Touch(b) = parse(&hex("32 68 e9 00 0b 50 e9 84 6c 13 84")) else { panic!() };
assert_eq!((a.x, b.x), (-22, 11));
assert!(b.y > a.y);
let Report::Touch(end) = parse(&hex("32 00 00 00 28 61 f4 00 00 00 67")) else { panic!() };
assert!(end.released);
}
#[test]
fn swipe_steps() {
let mut g = Gestures::default();
let frame = |x, y| TouchFrame { stamp: 0, x, y, size: [100, 100, 10], released: false };
assert_eq!(g.on_touch(&frame(-900, -500)), None);
assert_eq!(g.on_touch(&frame(-700, -480)), None);
assert_eq!(g.on_touch(&frame(-590, -470)), Some(Swipe::Right));
assert_eq!(g.on_touch(&frame(-300, -460)), None);
assert_eq!(g.on_touch(&frame(-280, -460)), Some(Swipe::Right));
// a button press without a finger on the pad must not swallow the next swipe
g.on_touch(&TouchFrame { released: true, ..frame(0, 0) });
g.on_button();
g.on_touch(&frame(0, 0));
assert_eq!(g.on_touch(&frame(400, 0)), Some(Swipe::Right));
// click during a touch suppresses
g.on_touch(&TouchFrame { released: true, ..frame(0, 0) });
g.on_touch(&frame(0, 0));
g.on_button();
assert_eq!(g.on_touch(&frame(0, 600)), None);
}
}

View File

@@ -0,0 +1,202 @@
//! Waking the machine from suspend with the remote.
//!
//! Two things have to be in place:
//! 1. The Bluetooth controller may wake the system: `power/wakeup = enabled`
//! on its USB device and the ports above it.
//! 2. The kernel keeps scanning for the remote while suspended. It does that
//! for devices on its connect list that carry the "remote wakeup" flag.
//! BlueZ sets both only through its HID plugins, which SmartFox disables
//! (they drop the Siri Remote's reports), so we send the two management
//! commands ourselves: Add Device (auto-connect) and Set Device Flags.
//!
//! The remote advertises with a rotating private address. Without controller
//! side address resolution (kernel "LL privacy") the kernel can't filter for
//! it while suspended and accepts every advert, so other Bluetooth devices
//! nearby may wake the machine too; the launcher puts it back to sleep then.
use std::os::fd::{AsRawFd, FromRawFd, OwnedFd};
use std::path::Path;
use std::time::{Duration, Instant};
use anyhow::{Context, Result, bail};
/// The remote as the kernel knows it.
#[derive(Debug, Clone, Copy)]
pub struct Target {
/// Controller index (hci0 -> 0).
pub index: u16,
/// Address as printed ("10:B9:..." -> [0x10, 0xB9, ...]).
pub addr: [u8; 6],
/// true: LE public identity address, false: LE random (static).
pub public: bool,
}
/// Enables wakeup on every Bluetooth controller's device and its parents
/// (USB device, hub, xHCI). Returns how many files were switched on.
pub fn enable_controller_wakeup() -> usize {
let mut changed = 0;
let Ok(entries) = std::fs::read_dir("/sys/class/bluetooth") else { return 0 };
for e in entries.flatten() {
let name = e.file_name().to_string_lossy().to_string();
if !name.starts_with("hci") || name.contains(':') {
continue;
}
let Ok(dev) = std::fs::canonicalize(e.path().join("device")) else { continue };
for dir in dev.ancestors().take_while(|d| d.starts_with("/sys/devices")) {
changed += enable(&dir.join("power/wakeup")) as usize;
}
}
changed
}
fn enable(file: &Path) -> bool {
match std::fs::read_to_string(file) {
Ok(v) if v.trim() == "disabled" => match std::fs::write(file, "enabled") {
Ok(()) => {
log::info!("wake: enabled {}", file.display());
true
}
Err(e) => {
log::warn!("wake: {}: {e}", file.display());
false
}
},
_ => false,
}
}
// ---- kernel Bluetooth management interface ---------------------------------------
const AF_BLUETOOTH: libc::c_int = 31;
const BTPROTO_HCI: libc::c_int = 1;
const HCI_CHANNEL_CONTROL: u16 = 3;
const HCI_DEV_NONE: u16 = 0xffff;
const MGMT_OP_ADD_DEVICE: u16 = 0x0033;
const MGMT_OP_SET_DEVICE_FLAGS: u16 = 0x0050;
const MGMT_EV_CMD_COMPLETE: u16 = 0x0001;
const MGMT_EV_CMD_STATUS: u16 = 0x0002;
const ADDR_LE_PUBLIC: u8 = 1;
const ADDR_LE_RANDOM: u8 = 2;
/// Add Device action: connect automatically whenever it advertises.
const ACTION_AUTO_CONNECT: u8 = 2;
const DEVICE_FLAG_REMOTE_WAKEUP: u32 = 1;
#[repr(C)]
struct SockaddrHci {
family: libc::sa_family_t,
dev: u16,
channel: u16,
}
struct Mgmt(OwnedFd);
impl Mgmt {
fn open() -> Result<Self> {
// SAFETY: plain socket/bind calls; the fd is owned right away.
unsafe {
let fd = libc::socket(AF_BLUETOOTH, libc::SOCK_RAW | libc::SOCK_CLOEXEC, BTPROTO_HCI);
if fd < 0 {
bail!("mgmt socket: {}", std::io::Error::last_os_error());
}
let fd = OwnedFd::from_raw_fd(fd);
let addr = SockaddrHci { family: AF_BLUETOOTH as _, dev: HCI_DEV_NONE, channel: HCI_CHANNEL_CONTROL };
let len = std::mem::size_of::<SockaddrHci>() as libc::socklen_t;
if libc::bind(fd.as_raw_fd(), &addr as *const _ as *const libc::sockaddr, len) < 0 {
bail!("mgmt bind: {}", std::io::Error::last_os_error());
}
Ok(Mgmt(fd))
}
}
/// Sends a command and waits for its completion; Err on a non-zero status.
fn call(&self, op: u16, index: u16, params: &[u8]) -> Result<()> {
let mut msg = Vec::with_capacity(6 + params.len());
msg.extend_from_slice(&op.to_le_bytes());
msg.extend_from_slice(&index.to_le_bytes());
msg.extend_from_slice(&(params.len() as u16).to_le_bytes());
msg.extend_from_slice(params);
// SAFETY: writing an initialised buffer to our own socket.
let n = unsafe { libc::write(self.0.as_raw_fd(), msg.as_ptr().cast(), msg.len()) };
if n != msg.len() as isize {
bail!("mgmt write: {}", std::io::Error::last_os_error());
}
let deadline = Instant::now() + Duration::from_secs(2);
let mut buf = [0u8; 512];
loop {
let left = deadline.saturating_duration_since(Instant::now());
if left.is_zero() {
bail!("mgmt {op:#06x}: no reply");
}
let mut pfd = libc::pollfd { fd: self.0.as_raw_fd(), events: libc::POLLIN, revents: 0 };
// SAFETY: one valid pollfd.
if unsafe { libc::poll(&mut pfd, 1, left.as_millis() as libc::c_int) } <= 0 {
continue;
}
// SAFETY: reading into our own buffer.
let n = unsafe { libc::read(self.0.as_raw_fd(), buf.as_mut_ptr().cast(), buf.len()) };
if n < 9 {
continue;
}
let ev = u16::from_le_bytes([buf[0], buf[1]]);
let ev_index = u16::from_le_bytes([buf[2], buf[3]]);
let opcode = u16::from_le_bytes([buf[6], buf[7]]);
let status = buf[8];
if (ev == MGMT_EV_CMD_COMPLETE || ev == MGMT_EV_CMD_STATUS) && opcode == op && ev_index == index {
if status != 0 {
bail!("mgmt {op:#06x}: status {status:#04x}{}", status_name(status));
}
return Ok(());
}
}
}
}
fn status_name(status: u8) -> &'static str {
match status {
0x01 => " (unknown command: kernel too old)",
0x0b => " (rejected)",
0x0c => " (not supported)",
0x0d => " (invalid parameters)",
0x11 => " (invalid index)",
_ => "",
}
}
/// mgmt_addr_info: address in little-endian byte order plus its type.
fn addr_info(t: &Target) -> [u8; 7] {
let mut out = [0u8; 7];
for (i, b) in t.addr.iter().rev().enumerate() {
out[i] = *b;
}
out[6] = if t.public { ADDR_LE_PUBLIC } else { ADDR_LE_RANDOM };
out
}
/// Lets the remote wake the machine: on the kernel's connect list, flagged
/// for remote wakeup. Safe to repeat.
pub fn allow_remote_wakeup(t: &Target) -> Result<()> {
let mgmt = Mgmt::open().context("Bluetooth management socket (needs root)")?;
let addr = addr_info(t);
let mut add = addr.to_vec();
add.push(ACTION_AUTO_CONNECT);
mgmt.call(MGMT_OP_ADD_DEVICE, t.index, &add).context("Add Device")?;
let mut flags = addr.to_vec();
flags.extend_from_slice(&DEVICE_FLAG_REMOTE_WAKEUP.to_le_bytes());
mgmt.call(MGMT_OP_SET_DEVICE_FLAGS, t.index, &flags).context("Set Device Flags (remote wakeup)")?;
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn address_is_little_endian() {
let t = Target { index: 0, addr: [0x10, 0xB9, 0xC4, 0x17, 0xC0, 0x0F], public: true };
assert_eq!(addr_info(&t), [0x0F, 0xC0, 0x17, 0xC4, 0xB9, 0x10, ADDR_LE_PUBLIC]);
}
}