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,927 @@
//! System backends for the settings screen: display modes (wlr-randr),
//! Bluetooth devices (bluetoothctl), Wi-Fi (iwd), network and device info.
//!
//! Off Linux (Windows dev builds), or with `SMARTFOX_DEMO_SYSTEM=1`, a demo
//! backend with in-memory state keeps the settings screen usable.
//! All calls can block for a moment, so run them off the UI thread.
use std::process::{Command, Stdio};
use std::sync::Mutex;
use std::time::{Duration, Instant};
use anyhow::{Context, Result, bail};
pub fn demo() -> bool {
!cfg!(target_os = "linux") || std::env::var_os("SMARTFOX_DEMO_SYSTEM").is_some()
}
/// Runs a command and returns its stdout; kills it after `timeout`.
fn run(prog: &str, args: &[&str], timeout: Duration) -> Result<String> {
let mut child = Command::new(prog)
.args(args)
.stdin(Stdio::null())
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.spawn()
.with_context(|| format!("starting {prog}"))?;
let deadline = Instant::now() + timeout;
loop {
if child.try_wait()?.is_some() {
break;
}
if Instant::now() >= deadline {
let _ = child.kill();
let _ = child.wait();
bail!("{prog} {} timed out", args.join(" "));
}
std::thread::sleep(Duration::from_millis(20));
}
let out = child.wait_with_output()?;
let stdout = strip_ansi(&String::from_utf8_lossy(&out.stdout));
if !out.status.success() {
let err = strip_ansi(&String::from_utf8_lossy(&out.stderr));
bail!("{prog} {}: {}", args.join(" "), err.trim());
}
Ok(stdout)
}
/// bluetoothctl colours its output even when it isn't a terminal.
fn strip_ansi(s: &str) -> String {
let mut out = String::with_capacity(s.len());
let mut chars = s.chars();
while let Some(c) = chars.next() {
if c == '\x1b' {
for c in chars.by_ref() {
if c.is_ascii_alphabetic() {
break;
}
}
} else if c != '\x01' && c != '\x02' {
out.push(c);
}
}
out
}
// ---- display ---------------------------------------------------------------
#[derive(Debug, Clone, PartialEq)]
pub struct Mode {
pub w: u32,
pub h: u32,
pub hz: f32,
pub preferred: bool,
}
impl Mode {
pub fn label(&self) -> String {
format!("{} × {} · {} Hz", self.w, self.h, fmt_hz(self.hz))
}
/// Short name of the format, e.g. "4K UHD".
pub fn name(&self) -> &'static str {
match (self.w, self.h) {
(3840, 2160) | (4096, 2160) => "4K UHD",
(2560, 1440) => "QHD",
(1920, 1080) => "Full HD",
(1280, 720) => "HD",
_ => "",
}
}
/// Key stored in settings.toml (`display_mode`).
pub fn key(&self) -> String {
format!("{}x{}@{:.3}", self.w, self.h, self.hz)
}
fn same(&self, other: &Mode) -> bool {
self.w == other.w && self.h == other.h && (self.hz - other.hz).abs() < 0.05
}
pub fn matches_key(&self, key: &str) -> bool {
parse_mode_key(key).is_some_and(|m| self.same(&m))
}
}
fn fmt_hz(hz: f32) -> String {
let r = (hz * 100.0).round() / 100.0;
if (r - r.round()).abs() < 0.005 { format!("{}", r.round() as u32) } else { format!("{r:.2}") }
}
fn parse_mode_key(key: &str) -> Option<Mode> {
let (size, hz) = key.split_once('@')?;
let (w, h) = size.split_once('x')?;
Some(Mode { w: w.parse().ok()?, h: h.parse().ok()?, hz: hz.trim_end_matches("Hz").parse().ok()?, preferred: false })
}
#[derive(Debug, Clone)]
pub struct Display {
pub output: String,
pub description: String,
pub modes: Vec<Mode>,
pub current: Option<usize>,
}
impl Display {
pub fn current_mode(&self) -> Option<&Mode> {
self.current.and_then(|i| self.modes.get(i))
}
}
/// Parses `wlr-randr` text output; the first output is the TV.
fn parse_wlr_randr(text: &str) -> Option<Display> {
let mut lines = text.lines();
let head = lines.find(|l| !l.trim().is_empty() && !l.starts_with(' '))?;
let (output, description) = match head.split_once(' ') {
Some((o, d)) => (o.to_string(), d.trim().trim_matches('"').to_string()),
None => (head.trim().to_string(), String::new()),
};
let mut modes: Vec<Mode> = Vec::new();
let mut current = None;
let mut in_modes = false;
for line in lines {
if !line.starts_with(' ') {
break; // next output
}
let t = line.trim();
if t == "Modes:" {
in_modes = true;
continue;
}
if !in_modes {
continue;
}
if !t.chars().next().is_some_and(|c| c.is_ascii_digit()) {
in_modes = false;
continue;
}
// "1920x1080 px, 60.000000 Hz (preferred, current)"
let Some((size, rest)) = t.split_once(" px,") else { continue };
let Some((w, h)) = size.split_once('x') else { continue };
let hz: f32 = rest.trim().split_whitespace().next().and_then(|v| v.parse().ok()).unwrap_or(60.0);
let flags = rest.split_once('(').map(|(_, f)| f).unwrap_or("");
let mode = Mode {
w: w.trim().parse().unwrap_or(0),
h: h.trim().parse().unwrap_or(0),
hz,
preferred: flags.contains("preferred"),
};
let is_current = flags.contains("current");
match modes.iter().position(|m| m.same(&mode)) {
Some(i) => {
modes[i].preferred |= mode.preferred;
if is_current {
current = Some(i);
}
}
None => {
modes.push(mode);
if is_current {
current = Some(modes.len() - 1);
}
}
}
}
// Biggest first; tiny legacy modes are not useful on a TV.
let cur = current.map(|i| modes[i].clone());
modes.retain(|m| (m.w >= 1024 && m.h >= 576) || cur.as_ref().is_some_and(|c| c.same(m)));
modes.sort_by(|a, b| (b.w * b.h).cmp(&(a.w * a.h)).then(b.hz.total_cmp(&a.hz)));
let current = cur.and_then(|c| modes.iter().position(|m| m.same(&c)));
Some(Display { output, description, modes, current })
}
static DEMO_DISPLAY: Mutex<Option<Display>> = Mutex::new(None);
fn demo_display() -> Display {
let mut guard = DEMO_DISPLAY.lock().unwrap();
guard
.get_or_insert_with(|| {
let m = |w, h, hz, preferred| Mode { w, h, hz, preferred };
Display {
output: "HDMI-A-1".into(),
description: "Fejlesztői mód (demó kijelző)".into(),
modes: vec![
m(3840, 2160, 60.0, true),
m(3840, 2160, 30.0, false),
m(2560, 1440, 60.0, false),
m(1920, 1080, 60.0, false),
m(1920, 1080, 50.0, false),
m(1280, 720, 60.0, false),
],
current: Some(3),
}
})
.clone()
}
pub fn display() -> Result<Display> {
if demo() {
return Ok(demo_display());
}
let out = run("wlr-randr", &[], Duration::from_secs(3))?;
parse_wlr_randr(&out).context("wlr-randr: no output found")
}
pub fn set_mode(output: &str, mode: &Mode) -> Result<()> {
if demo() {
let mut guard = DEMO_DISPLAY.lock().unwrap();
if let Some(d) = guard.as_mut() {
d.current = d.modes.iter().position(|m| m.same(mode));
}
return Ok(());
}
let arg = format!("{}x{}@{}Hz", mode.w, mode.h, mode.hz);
run("wlr-randr", &["--output", output, "--mode", &arg], Duration::from_secs(5))?;
Ok(())
}
/// Applies the saved `display_mode` at startup, if the TV offers it.
pub fn apply_saved_mode(key: &str) -> Result<()> {
let d = display()?;
let Some(mode) = d.modes.iter().find(|m| m.matches_key(key)) else {
bail!("saved mode {key} is not offered by {}", d.output);
};
if d.current_mode().is_some_and(|c| c.same(mode)) {
return Ok(());
}
log::info!("display: applying saved mode {}", mode.label());
set_mode(&d.output, mode)
}
/// Standby: switches the TV signal off or back on. `saved` is the
/// `display_mode` to restore after the output comes back.
pub fn display_power(on: bool, saved: Option<&str>) -> Result<()> {
if demo() || std::env::var_os("WAYLAND_DISPLAY").is_none() {
return Ok(());
}
let t = Duration::from_secs(4);
// DPMS keeps the mode; only if the compositor offers it (wlopm installed).
let state = if on { "--on" } else { "--off" };
if run("wlopm", &[state, "*"], t).is_ok() {
return Ok(());
}
// Otherwise disable the output (cage supports wlr-output-management).
let head = run("wlr-randr", &[], t)?;
let output = parse_wlr_randr(&head).context("wlr-randr: no output found")?.output;
run("wlr-randr", &["--output", &output, state], t)?;
if on {
if let Some(key) = saved {
apply_saved_mode(key)?;
}
}
Ok(())
}
/// Whether the Bluetooth controller may wake the machine (USB `power/wakeup`).
/// sf-remote (root) turns this on before suspending.
#[derive(Debug, Clone, PartialEq)]
pub enum BtWake {
NoController,
Enabled,
/// Off now; sf-remote enables it before each suspend.
Disabled,
Unknown,
}
pub fn bt_wake() -> BtWake {
if demo() {
return BtWake::Enabled;
}
let Ok(entries) = std::fs::read_dir("/sys/class/bluetooth") else { return BtWake::NoController };
let mut found = false;
for e in entries.flatten() {
let name = e.file_name().to_string_lossy().to_string();
if !name.starts_with("hci") || name.contains(':') {
continue;
}
found = true;
let Ok(dev) = std::fs::canonicalize(e.path().join("device")) else { continue };
if let Some(v) = dev.ancestors().find_map(|a| std::fs::read_to_string(a.join("power/wakeup")).ok()) {
return if v.trim() == "enabled" { BtWake::Enabled } else { BtWake::Disabled };
}
}
if found { BtWake::Unknown } else { BtWake::NoController }
}
// ---- bluetooth -----------------------------------------------------------
#[derive(Debug, Clone)]
pub struct BtDevice {
pub address: String,
pub name: String,
pub connected: bool,
pub battery: Option<u8>,
/// An Apple Siri Remote (the one sf-remote drives).
pub remote: bool,
pub icon: String,
}
impl BtDevice {
pub fn status(&self) -> String {
match (self.connected, self.battery) {
(true, Some(b)) => format!("Csatlakozva · {b}%"),
(true, None) => "Csatlakozva".into(),
(false, _) if self.remote => "Alszik · nyomj meg egy gombot".into(),
(false, _) => "Nincs csatlakozva".into(),
}
}
pub fn kind_label(&self) -> &'static str {
if self.remote {
return "Siri Remote";
}
match self.icon.as_str() {
"audio-headphones" | "audio-headset" => "Fejhallgató",
"audio-card" | "audio-speakers" => "Hangszóró",
"input-gaming" => "Játékvezérlő",
"input-keyboard" => "Billentyűzet",
"input-mouse" => "Egér",
"phone" => "Telefon",
_ => "Bluetooth eszköz",
}
}
}
fn is_mac(s: &str) -> bool {
s.len() == 17 && s.split(':').count() == 6 && s.split(':').all(|p| p.len() == 2 && p.chars().all(|c| c.is_ascii_hexdigit()))
}
/// "Device AA:BB:CC:DD:EE:FF Name" lines.
fn parse_device_list(text: &str) -> Vec<(String, String)> {
text.lines()
.filter_map(|l| {
let rest = &l[l.find("Device ")? + "Device ".len()..];
let (addr, name) = rest.split_once(' ').unwrap_or((rest, ""));
is_mac(addr).then(|| (addr.to_string(), name.trim().to_string()))
})
.collect()
}
fn parse_info(addr: &str, fallback_name: &str, text: &str) -> BtDevice {
let field = |key: &str| {
text.lines()
.map(str::trim)
.find_map(|l| l.strip_prefix(key).map(|v| v.trim().to_string()))
};
let name = field("Alias:").or_else(|| field("Name:")).unwrap_or_else(|| fallback_name.to_string());
let connected = field("Connected:").is_some_and(|v| v == "yes");
// "Battery Percentage: 0x5a (90)"
let battery = field("Battery Percentage:")
.and_then(|v| v.split_once('(').and_then(|(_, p)| p.trim_end_matches(')').parse().ok()));
// "Modalias: bluetooth:v004Cp0315d0001" (vendor 004C = Apple)
let modalias = field("Modalias:").unwrap_or_default().to_ascii_lowercase();
let remote = ["p0314", "p0315", "p0266"].iter().any(|p| modalias.contains(&format!("v004c{p}")));
let icon = field("Icon:").unwrap_or_default();
BtDevice { address: addr.to_string(), name, connected, battery, remote, icon }
}
static DEMO_DEVICES: Mutex<Option<Vec<BtDevice>>> = Mutex::new(None);
fn demo_devices() -> Vec<BtDevice> {
DEMO_DEVICES
.lock()
.unwrap()
.get_or_insert_with(|| {
vec![
BtDevice {
address: "F0:B3:EC:12:7A:41".into(),
name: "Siri Remote".into(),
connected: true,
battery: Some(82),
remote: true,
icon: "input-gaming".into(),
},
BtDevice {
address: "4C:87:5D:0E:22:9B".into(),
name: "AirPods Pro".into(),
connected: false,
battery: None,
remote: false,
icon: "audio-headphones".into(),
},
]
})
.clone()
}
pub fn bt_devices() -> Result<Vec<BtDevice>> {
if demo() {
return Ok(demo_devices());
}
let t = Duration::from_secs(4);
let list = match run("bluetoothctl", &["devices", "Paired"], t) {
Ok(out) if !parse_device_list(&out).is_empty() => out,
// Older BlueZ.
_ => run("bluetoothctl", &["paired-devices"], t).unwrap_or_default(),
};
let mut devices = Vec::new();
for (addr, name) in parse_device_list(&list) {
let info = run("bluetoothctl", &["info", &addr], t).unwrap_or_default();
devices.push(parse_info(&addr, &name, &info));
}
// Remotes first, then connected devices.
devices.sort_by_key(|d| (!d.remote, !d.connected, d.name.to_lowercase()));
Ok(devices)
}
pub fn bt_remove(addr: &str) -> Result<()> {
if demo() {
if let Some(list) = DEMO_DEVICES.lock().unwrap().as_mut() {
list.retain(|d| d.address != addr);
}
return Ok(());
}
let out = run("bluetoothctl", &["remove", addr], Duration::from_secs(6))?;
if out.contains("not available") || out.contains("Failed") {
bail!("{}", out.trim());
}
Ok(())
}
// ---- network & device info -------------------------------------------------
#[derive(Debug, Clone, Default)]
pub struct NetInfo {
pub iface: Option<String>,
pub wireless: bool,
pub ip: Option<String>,
pub gateway: Option<String>,
pub wifi_adapter: bool,
}
pub fn network() -> NetInfo {
if demo() {
return NetInfo {
iface: Some("enp1s0".into()),
wireless: false,
ip: Some("192.168.1.42".into()),
gateway: Some("192.168.1.1".into()),
wifi_adapter: true,
};
}
let t = Duration::from_secs(2);
let mut info = NetInfo::default();
// "2: enp1s0 inet 192.168.1.42/24 brd ... "
if let Ok(out) = run("ip", &["-o", "-4", "addr", "show", "scope", "global"], t) {
if let Some(line) = out.lines().next() {
let f: Vec<&str> = line.split_whitespace().collect();
info.iface = f.get(1).map(|s| s.to_string());
info.ip = f.get(3).map(|s| s.split('/').next().unwrap_or(s).to_string());
}
}
// "default via 192.168.1.1 dev enp1s0 ..."
if let Ok(out) = run("ip", &["route", "show", "default"], t) {
let f: Vec<&str> = out.split_whitespace().collect();
info.gateway = f.iter().position(|w| *w == "via").and_then(|i| f.get(i + 1)).map(|s| s.to_string());
}
let wireless = |iface: &str| std::path::Path::new("/sys/class/net").join(iface).join("wireless").exists();
info.wireless = info.iface.as_deref().is_some_and(wireless);
info.wifi_adapter = std::fs::read_dir("/sys/class/net")
.map(|d| d.flatten().any(|e| wireless(&e.file_name().to_string_lossy())))
.unwrap_or(false);
info
}
// ---- wi-fi (iwd over D-Bus) -------------------------------------------------
//
// Reads go through `busctl --json` (the whole iwd object tree in one call).
// A new password needs an agent, which `iwctl --passphrase` provides; known
// and open networks connect with a plain D-Bus call. The tv user reaches iwd
// through the netdev group (iwd's D-Bus policy).
const IWD: &str = "net.connman.iwd";
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum Security {
Open,
Psk,
Wep,
Enterprise,
}
#[derive(Debug, Clone, PartialEq)]
pub struct WifiNetwork {
/// D-Bus object path, stable while the network is in range.
pub path: String,
pub name: String,
pub security: Security,
/// dBm.
pub signal: i32,
pub connected: bool,
/// KnownNetwork object path when a password is saved.
pub known: Option<String>,
}
impl WifiNetwork {
pub fn bars(&self) -> i32 {
match self.signal {
s if s >= -60 => 4,
s if s >= -67 => 3,
s if s >= -75 => 2,
_ => 1,
}
}
pub fn strength_label(&self) -> &'static str {
["", "Gyenge", "Közepes", "Jó", "Kiváló"][self.bars() as usize]
}
pub fn security_label(&self) -> &'static str {
match self.security {
Security::Open => "Nyílt hálózat",
Security::Psk => "Jelszóval védett",
Security::Wep => "WEP (elavult)",
Security::Enterprise => "Vállalati (802.1X)",
}
}
}
#[derive(Debug, Clone, Default, PartialEq)]
pub struct Wifi {
/// iwd Device object path.
pub device: String,
/// Interface name, e.g. "wlan0".
pub iface: String,
pub powered: bool,
pub scanning: bool,
/// Strongest first, the connected one on top.
pub networks: Vec<WifiNetwork>,
}
fn busctl(args: &[&str], timeout: Duration) -> Result<serde_json::Value> {
let mut all = vec!["--json=short"];
all.extend_from_slice(args);
let out = run("busctl", &all, timeout).map_err(|e| {
let text = format!("{e:#}");
if text.contains("not provided by any") || text.contains("ServiceUnknown") || text.contains("was not provided") {
anyhow::anyhow!("a Wi-Fi szolgáltatás (iwd) nem fut")
} else {
e
}
})?;
if out.trim().is_empty() {
return Ok(serde_json::Value::Null);
}
serde_json::from_str(&out).context("busctl: unexpected output")
}
/// One D-Bus property from a GetManagedObjects entry.
fn prop<'a>(obj: &'a serde_json::Value, iface: &str, name: &str) -> Option<&'a serde_json::Value> {
obj.get(iface)?.get(name)?.get("data")
}
/// Builds the state from `GetManagedObjects` data and the ordered
/// (network path, signal in 100 * dBm) list of the station.
fn parse_wifi(objects: &serde_json::Value, ordered: &[(String, i64)]) -> Option<Wifi> {
let objs = objects.as_object()?;
let (device, dev) = objs
.iter()
.filter(|(_, o)| o.get("net.connman.iwd.Device").is_some())
.min_by_key(|(p, _)| p.len())?;
let text = |o: &serde_json::Value, i: &str, n: &str| prop(o, i, n).and_then(|v| v.as_str()).unwrap_or("").to_string();
let flag = |o: &serde_json::Value, i: &str, n: &str| prop(o, i, n).and_then(|v| v.as_bool()).unwrap_or(false);
let mut wifi = Wifi {
device: device.clone(),
iface: text(dev, "net.connman.iwd.Device", "Name"),
powered: flag(dev, "net.connman.iwd.Device", "Powered"),
scanning: flag(dev, "net.connman.iwd.Station", "Scanning"),
networks: Vec::new(),
};
for (path, signal) in ordered {
let Some(net) = objs.get(path) else { continue };
let name = text(net, "net.connman.iwd.Network", "Name");
if name.is_empty() {
continue;
}
let security = match text(net, "net.connman.iwd.Network", "Type").as_str() {
"open" | "owe" => Security::Open,
"wep" => Security::Wep,
"8021x" => Security::Enterprise,
_ => Security::Psk,
};
wifi.networks.push(WifiNetwork {
path: path.clone(),
name,
security,
signal: (*signal / 100) as i32,
connected: flag(net, "net.connman.iwd.Network", "Connected"),
known: prop(net, "net.connman.iwd.Network", "KnownNetwork").and_then(|v| v.as_str()).map(str::to_string),
});
}
// Stable sort keeps iwd's signal order inside each group.
wifi.networks.sort_by_key(|n| !n.connected);
Some(wifi)
}
static DEMO_WIFI: Mutex<Option<Wifi>> = Mutex::new(None);
fn with_demo_wifi<T>(f: impl FnOnce(&mut Wifi) -> T) -> T {
let mut guard = DEMO_WIFI.lock().unwrap();
let wifi = guard.get_or_insert_with(|| {
let n = |i: usize, name: &str, security, signal, known: bool| WifiNetwork {
path: format!("/net/connman/iwd/0/4/demo{i}"),
name: name.into(),
security,
signal,
connected: false,
known: known.then(|| format!("/net/connman/iwd/known/demo{i}")),
};
Wifi {
device: "/net/connman/iwd/0/4".into(),
iface: "wlan0".into(),
powered: true,
scanning: false,
networks: vec![
n(1, "Otthon-5G", Security::Psk, -48, false),
n(2, "Otthon", Security::Psk, -58, true),
n(3, "Kávézó vendég", Security::Open, -69, false),
n(4, "Szomszéd_WiFi", Security::Psk, -77, false),
n(5, "Iroda", Security::Enterprise, -81, false),
],
}
});
f(wifi)
}
/// Ok(None) when there is no Wi-Fi adapter.
pub fn wifi() -> Result<Option<Wifi>> {
if demo() {
return Ok(Some(with_demo_wifi(|w| {
let mut w = w.clone();
if !w.powered {
w.networks.clear();
}
w
})));
}
let t = Duration::from_secs(3);
let objects = busctl(&["call", IWD, "/", "org.freedesktop.DBus.ObjectManager", "GetManagedObjects"], t)?;
let objects = &objects["data"][0];
let station = objects.as_object().and_then(|o| {
o.iter()
.filter(|(_, v)| v.get("net.connman.iwd.Station").is_some())
.map(|(p, _)| p.clone())
.min_by_key(|p| p.len())
});
let mut ordered = Vec::new();
if let Some(station) = station {
// {"type":"a(on)","data":[[["/net/connman/iwd/0/4/..._psk",-5400], ...]]}
let v = busctl(&["call", IWD, &station, "net.connman.iwd.Station", "GetOrderedNetworks"], t)?;
if let Some(list) = v["data"][0].as_array() {
for item in list {
if let (Some(p), Some(s)) = (item[0].as_str(), item[1].as_i64()) {
ordered.push((p.to_string(), s));
}
}
}
}
Ok(parse_wifi(objects, &ordered))
}
/// Starts a scan; results show up in `wifi()` a few seconds later.
pub fn wifi_scan(device: &str) -> Result<()> {
if demo() {
return Ok(());
}
match busctl(&["call", IWD, device, "net.connman.iwd.Station", "Scan"], Duration::from_secs(5)) {
Err(e) if format!("{e:#}").contains("InProgress") => Ok(()),
r => r.map(|_| ()),
}
}
pub fn wifi_set_powered(device: &str, on: bool) -> Result<()> {
if demo() {
with_demo_wifi(|w| w.powered = on);
return Ok(());
}
let t = Duration::from_secs(5);
let value = if on { "true" } else { "false" };
if on {
// The adapter (radio) has to be on before the device can be.
let adapter = busctl(&["get-property", IWD, device, "net.connman.iwd.Device", "Adapter"], t)?;
if let Some(adapter) = adapter["data"].as_str() {
busctl(&["set-property", IWD, adapter, "net.connman.iwd.Adapter", "Powered", "b", "true"], t)?;
}
}
busctl(&["set-property", IWD, device, "net.connman.iwd.Device", "Powered", "b", value], t)?;
Ok(())
}
/// Connects and waits until iwd reports the network connected.
/// `passphrase` is needed only for a protected network that isn't saved yet.
pub fn wifi_connect(iface: &str, net: &WifiNetwork, passphrase: Option<&str>) -> Result<()> {
if demo() {
std::thread::sleep(Duration::from_millis(1500));
if passphrase.is_some_and(|p| p == "rosszjelszo") {
bail!("hibás jelszó");
}
with_demo_wifi(|w| {
for n in &mut w.networks {
n.connected = n.path == net.path;
if n.connected && n.known.is_none() && n.security != Security::Open {
n.known = Some(format!("/net/connman/iwd/known/{}", n.name));
}
}
w.networks.sort_by_key(|n| !n.connected);
});
return Ok(());
}
let t = Duration::from_secs(40);
let attempt = match passphrase {
Some(p) => run("iwctl", &["--passphrase", p, "station", iface, "connect", &net.name], t),
None => busctl(&["call", IWD, &net.path, "net.connman.iwd.Network", "Connect"], t).map(|_| String::new()),
};
// iwctl doesn't always exit non-zero on failure: trust iwd's state instead.
let connected = wifi().ok().flatten().is_some_and(|w| w.networks.iter().any(|n| n.connected && n.name == net.name));
if connected {
return Ok(());
}
let detail = match attempt {
Ok(out) => out.trim().to_string(),
Err(e) => format!("{e:#}"),
};
log::warn!("wifi: connecting to {} failed: {detail}", net.name);
if passphrase.is_some() || detail.contains("Failed") || detail.contains("Operation failed") {
bail!("hibás jelszó, vagy a hálózat nem érhető el");
}
bail!("{}", if detail.is_empty() { "a kapcsolat nem jött létre".to_string() } else { detail })
}
pub fn wifi_disconnect(device: &str) -> Result<()> {
if demo() {
with_demo_wifi(|w| w.networks.iter_mut().for_each(|n| n.connected = false));
return Ok(());
}
busctl(&["call", IWD, device, "net.connman.iwd.Station", "Disconnect"], Duration::from_secs(10))?;
Ok(())
}
/// Deletes the saved password (and disconnects if it is the current network).
pub fn wifi_forget(known: &str) -> Result<()> {
if demo() {
with_demo_wifi(|w| {
for n in &mut w.networks {
if n.known.as_deref() == Some(known) {
n.known = None;
n.connected = false;
}
}
});
return Ok(());
}
busctl(&["call", IWD, known, "net.connman.iwd.KnownNetwork", "Forget"], Duration::from_secs(10))?;
Ok(())
}
#[derive(Debug, Clone, Default)]
pub struct DeviceInfo {
pub hostname: String,
pub os: String,
pub kernel: String,
}
pub fn device_info() -> DeviceInfo {
if !cfg!(target_os = "linux") {
return DeviceInfo {
hostname: std::env::var("COMPUTERNAME").unwrap_or_else(|_| "smartfox".into()).to_lowercase(),
os: "Windows (fejlesztői mód)".into(),
kernel: "-".into(),
};
}
let read = |p: &str| std::fs::read_to_string(p).unwrap_or_default().trim().to_string();
let os = read("/etc/os-release")
.lines()
.find_map(|l| l.strip_prefix("PRETTY_NAME=").map(|v| v.trim_matches('"').to_string()))
.unwrap_or_else(|| "Linux".into());
DeviceInfo { hostname: read("/etc/hostname"), os, kernel: read("/proc/sys/kernel/osrelease") }
}
// ---- remote debugging (ssh) ----------------------------------------------
/// The launcher runs as `tv`, so it can't start sshd itself: it writes this
/// flag and sf-remote-debug.path (root) starts or stops ssh.service.
const DEBUG_FLAG: &str = "/var/lib/smartfox/remote-debug";
static DEMO_DEBUG: Mutex<bool> = Mutex::new(false);
#[derive(Debug, Clone, Default, PartialEq)]
pub struct RemoteDebug {
/// sshd is running.
pub on: bool,
/// When it turns off by itself ("21:45"); None without a time limit (VM).
pub until: Option<String>,
}
pub fn remote_debug() -> RemoteDebug {
if demo() {
let on = *DEMO_DEBUG.lock().unwrap();
return RemoteDebug { on, until: on.then(|| "21:45".into()) };
}
let t = Duration::from_secs(2);
// `is-active` exits non-zero unless the unit is active.
let on = run("systemctl", &["is-active", "ssh.service"], t).is_ok();
let until = if on {
run("systemctl", &["show", "sf-remote-debug-off.timer", "--property=NextElapseUSecRealtime", "--value"], t)
.ok()
.and_then(|v| clock(&v))
} else {
None
};
RemoteDebug { on, until }
}
/// "Fri 2026-10-23 21:45:00 CEST" -> "21:45".
fn clock(timestamp: &str) -> Option<String> {
timestamp
.split_whitespace()
.find(|w| w.len() == 8 && w.as_bytes()[2] == b':' && w.as_bytes()[5] == b':')
.map(|w| w[..5].to_string())
}
/// Turns sshd on or off and waits until it has happened.
pub fn set_remote_debug(on: bool) -> Result<()> {
if demo() {
*DEMO_DEBUG.lock().unwrap() = on;
return Ok(());
}
std::fs::write(DEBUG_FLAG, if on { "on\n" } else { "off\n" }).with_context(|| format!("writing {DEBUG_FLAG}"))?;
let deadline = Instant::now() + Duration::from_secs(8);
while Instant::now() < deadline {
if remote_debug().on == on {
return Ok(());
}
std::thread::sleep(Duration::from_millis(250));
}
bail!("ssh.service is still {}", if on { "stopped" } else { "running" })
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn parses_wlr_randr() {
let text = "HDMI-A-1 \"Samsung Electric Company SAMSUNG (HDMI-A-1)\"\n Enabled: yes\n Modes:\n 3840x2160 px, 30.000000 Hz\n 1920x1080 px, 60.000000 Hz (preferred, current)\n 1920x1080 px, 59.940002 Hz\n 3840x2160 px, 60.000000 Hz\n 720x400 px, 70.082001 Hz\n Position: 0,0\n Transform: normal\n Scale: 1.000000\n";
let d = parse_wlr_randr(text).unwrap();
assert_eq!(d.output, "HDMI-A-1");
assert!(d.description.starts_with("Samsung"));
assert_eq!(d.modes.len(), 4);
assert_eq!((d.modes[0].w, d.modes[0].hz), (3840, 60.0));
let cur = d.current_mode().unwrap();
assert_eq!((cur.w, cur.h, cur.preferred), (1920, 1080, true));
assert_eq!(cur.label(), "1920 × 1080 · 60 Hz");
assert_eq!(d.modes[3].label(), "1920 × 1080 · 59.94 Hz");
assert!(cur.matches_key(&cur.key()));
}
#[test]
fn parses_bluetoothctl() {
let list = "\x1b[0;94m[bluetooth]\x1b[0m# Device F0:B3:EC:12:7A:41 Siri Remote\nDevice 4C:87:5D:0E:22:9B AirPods Pro\nnoise";
let devs = parse_device_list(&strip_ansi(list));
assert_eq!(devs.len(), 2);
assert_eq!(devs[0], ("F0:B3:EC:12:7A:41".into(), "Siri Remote".into()));
let info = "Device F0:B3:EC:12:7A:41 (public)\n\tName: Siri Remote\n\tAlias: Nappali távirányító\n\tIcon: input-gaming\n\tConnected: yes\n\tModalias: bluetooth:v004Cp0315d0001\n\tBattery Percentage: 0x52 (82)\n";
let d = parse_info("F0:B3:EC:12:7A:41", "x", info);
assert!(d.remote && d.connected);
assert_eq!(d.battery, Some(82));
assert_eq!(d.name, "Nappali távirányító");
}
#[test]
fn parses_iwd_objects() {
let objects: serde_json::Value = serde_json::from_str(
r#"{
"/net/connman/iwd/0": {"net.connman.iwd.Adapter": {"Powered": {"type":"b","data":true}}},
"/net/connman/iwd/0/4": {
"net.connman.iwd.Device": {"Name": {"type":"s","data":"wlan0"}, "Powered": {"type":"b","data":true}, "Mode": {"type":"s","data":"station"}},
"net.connman.iwd.Station": {"State": {"type":"s","data":"connected"}, "Scanning": {"type":"b","data":false}}
},
"/net/connman/iwd/0/4/4f74686f6e_psk": {"net.connman.iwd.Network": {
"Name": {"type":"s","data":"Otthon"}, "Type": {"type":"s","data":"psk"}, "Connected": {"type":"b","data":true},
"KnownNetwork": {"type":"o","data":"/net/connman/iwd/4f74686f6e_psk"}}},
"/net/connman/iwd/0/4/4b617665_open": {"net.connman.iwd.Network": {
"Name": {"type":"s","data":"Kávé"}, "Type": {"type":"s","data":"open"}, "Connected": {"type":"b","data":false}}}
}"#,
)
.unwrap();
let ordered = vec![
("/net/connman/iwd/0/4/4b617665_open".to_string(), -4500),
("/net/connman/iwd/0/4/4f74686f6e_psk".to_string(), -7000),
];
let w = parse_wifi(&objects, &ordered).unwrap();
assert_eq!((w.iface.as_str(), w.powered, w.device.as_str()), ("wlan0", true, "/net/connman/iwd/0/4"));
assert_eq!(w.networks.len(), 2);
// Connected first, then by signal.
assert_eq!(w.networks[0].name, "Otthon");
assert!(w.networks[0].connected && w.networks[0].known.is_some());
assert_eq!((w.networks[0].signal, w.networks[0].bars()), (-70, 2));
assert_eq!((w.networks[1].security, w.networks[1].bars()), (Security::Open, 4));
assert!(parse_wifi(&serde_json::json!({}), &[]).is_none());
}
#[test]
fn parses_timer_clock() {
assert_eq!(clock("Fri 2026-10-23 21:45:07 CEST\n").as_deref(), Some("21:45"));
assert_eq!(clock(""), None);
}
}