diff --git a/CLAUDE.md b/CLAUDE.md index cfb272d..9c13eb2 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -21,6 +21,8 @@ cargo test some_test_name # run tests matching a name `.githooks/pre-commit` runs `cargo fmt --check`, `cargo clippy --all-targets --all-features -- -D warnings`, and `cargo test`, the same checks CI runs (`.github/workflows/ci.yml`). Run these before committing; there is no separate lint/typecheck step to remember. +`cargo run --release --example eq_probe -- ` switches one equalizer preset on real hardware and restores it afterwards (close the GUI first: the earbuds accept a single RFCOMM connection). Models whose equalizer is TWS-gated (e.g. A3949/K20i) only expose it when both earbuds are connected; otherwise the settings read as absent and writes are silently ignored by `openscq30-lib`. + If more than one compatible device is visible, `SOUNDCORE_CONTROL_MAC=AA:BB:CC:DD:EE:FF` selects one (read via `device::configured_mac_address()`, used by both the device worker and the Bluetooth watcher). Runtime state lives in `${XDG_DATA_HOME:-~/.local/share}/soundcore-control/devices.sqlite3` (OpenSCQ30's device database, not app-specific config). `device::database_path()` transparently migrates an old `liberty-control` data directory on first launch if found. diff --git a/assets/devices.toml b/assets/devices.toml index 58497ce..e2580a2 100644 --- a/assets/devices.toml +++ b/assets/devices.toml @@ -9,11 +9,24 @@ # trusting it. # `icon` (optional) names a PNG file in assets/icons/; omit it to fall back to the # generic vector-drawn placeholder. +# `read_only_controls` (optional, default false) hides daily/button controls and drops their +# writes. Use it for models aliased onto a similar `openscq30-lib` model whose state packet +# only partly matches, where those controls would be misparsed. # `supports_manual_ambient_ranges` must be `true` only for devices confirmed to expose # separate ManualNoiseCanceling/ManualTransparency numeric-range settings. Setting it to # true for a device that doesn't have them makes openscq30-lib panic on connect (see # device::initialize_ambient_level). Default to `false` for anything unverified. +# Not supported by openscq30-lib; the state packet matches A3949 (P20i) except for the button +# section (1 byte per button), so daily/button controls are hidden. Must come before any +# entry that could match by MAC alone (SOUNDCORE_CONTROL_MAC). +[[device]] +model = "SoundcoreA3949" +bluetooth_name = "soundcore K20i" +display_name = "K20i" +supports_manual_ambient_ranges = false +read_only_controls = true + [[device]] model = "SoundcoreA3954" bluetooth_name = "soundcore Liberty 4 Pro" diff --git a/examples/eq_probe.rs b/examples/eq_probe.rs new file mode 100644 index 0000000..e057bb4 --- /dev/null +++ b/examples/eq_probe.rs @@ -0,0 +1,112 @@ +//! Hardware probe for equalizer writes on an aliased model (e.g. K20i mapped to A3949). +//! +//! Connects to one device by MAC, reads the equalizer state, switches to a different preset, +//! waits for the earbuds to report back, prints what changed, then restores the original +//! preset. Close the GUI first: the earbuds accept a single RFCOMM connection. +//! +//! ```text +//! RUST_LOG=debug cargo run --release --example eq_probe -- AA:BB:CC:DD:EE:FF SoundcoreA3949 BassBooster +//! ``` + +use std::{borrow::Cow, time::Duration}; + +use anyhow::{Context, Result, anyhow}; +use openscq30_lib::{ + DeviceModel, OpenSCQ30Session, + device::OpenSCQ30Device, + settings::{Setting, SettingId, Value}, + storage::PairedDevice, +}; + +fn describe(device: &dyn OpenSCQ30Device) -> String { + let preset = match device.setting(&SettingId::PresetEqualizerProfile) { + Some(Setting::PresetEqualizerProfileSelect { value, .. }) => value.map(Cow::into_owned), + _ => None, + }; + let bands = match device.setting(&SettingId::VolumeAdjustments) { + Some(Setting::Equalizer { value, .. }) => Some(value), + _ => None, + }; + format!("preset={preset:?} bands={bands:?}") +} + +#[tokio::main] +async fn main() -> Result<()> { + tracing_subscriber::fmt() + .with_env_filter(tracing_subscriber::EnvFilter::from_default_env()) + .init(); + + let mut args = std::env::args().skip(1); + let mac = args + .next() + .context("usage: eq_probe ")?; + let model: DeviceModel = args + .next() + .context("missing DeviceModel")? + .parse() + .map_err(|_| anyhow!("unknown DeviceModel"))?; + let target = args.next().context("missing preset name")?; + + // Throwaway database so the probe never touches the app's paired-device data. + let database = std::env::temp_dir().join("soundcore-eq-probe.sqlite3"); + let session = OpenSCQ30Session::new(database).await?; + session + .pair(PairedDevice { + mac_address: mac.parse().context("invalid MAC")?, + model, + is_demo: false, + }) + .await?; + let device = session.connect(mac.parse()?).await?; + + for id in [ + SettingId::PresetEqualizerProfile, + SettingId::CustomEqualizerProfile, + SettingId::VolumeAdjustments, + ] { + println!("raw {id:?}: {:?}", device.setting(&id)); + } + let before = describe(device.as_ref()); + println!("before : {before}"); + let original = match device.setting(&SettingId::PresetEqualizerProfile) { + Some(Setting::PresetEqualizerProfileSelect { + value: Some(value), .. + }) => value.into_owned(), + _ => { + return Err(anyhow!( + "device reports no current preset; refusing to write" + )); + } + }; + if original == target { + return Err(anyhow!("already on '{target}'; pick a different preset")); + } + + let result = write_and_report(device.as_ref(), &target).await; + // Always try to put the original preset back, even if the write above failed. + let restore = device + .set_setting_values(vec![( + SettingId::PresetEqualizerProfile, + Value::String(Cow::Owned(original.clone())), + )]) + .await; + tokio::time::sleep(Duration::from_secs(2)).await; + println!( + "restored: {} (restore result: {restore:?})", + describe(device.as_ref()) + ); + result +} + +async fn write_and_report(device: &dyn OpenSCQ30Device, target: &str) -> Result<()> { + device + .set_setting_values(vec![( + SettingId::PresetEqualizerProfile, + Value::String(Cow::Owned(target.to_owned())), + )]) + .await + .context("device rejected the preset write")?; + tokio::time::sleep(Duration::from_secs(2)).await; + println!("after : {}", describe(device)); + Ok(()) +} diff --git a/src/device.rs b/src/device.rs index 042cb60..ebe2748 100644 --- a/src/device.rs +++ b/src/device.rs @@ -148,7 +148,7 @@ async fn run_device( .await .context("could not open the Soundcore RFCOMM service")?; initialize_ambient_level(device.as_ref(), events, profile).await; - let snapshot = read_snapshot(device.as_ref()); + let snapshot = read_snapshot(device.as_ref(), profile.read_only_controls); events .send(DeviceEvent::Connected { name: profile.display_name.to_owned(), @@ -158,7 +158,14 @@ async fn run_device( }) .ok(); - event_loop(device, descriptor.mac_address, &mut commands, events).await + event_loop( + device, + descriptor.mac_address, + profile.read_only_controls, + &mut commands, + events, + ) + .await } /// Tries each known device profile in turn, querying BlueZ for devices of that model until @@ -195,6 +202,7 @@ async fn find_target_device( async fn event_loop( device: Arc, mac_address: MacAddr6, + read_only_controls: bool, commands: &mut tokio_mpsc::UnboundedReceiver, events: &mpsc::Sender, ) -> Result<()> { @@ -217,6 +225,10 @@ async fn event_loop( } continue; } + if read_only_controls && is_control_write(&command) { + tracing::warn!(?command, "dropping control write for a read-only-controls profile"); + continue; + } for change in setting_changes(command) { if let Err(error) = device.set_setting_values(vec![change]).await { events.send(DeviceEvent::Error(format!("Could not update the earbuds: {error}"))).ok(); @@ -229,7 +241,7 @@ async fn event_loop( events.send(DeviceEvent::Disconnected).ok(); return Ok(()); } - events.send(DeviceEvent::Snapshot(read_snapshot(device.as_ref()))).ok(); + events.send(DeviceEvent::Snapshot(read_snapshot(device.as_ref(), read_only_controls))).ok(); } changed = connection.changed() => { if changed.is_err() || matches!(*connection.borrow(), openscq30_lib::connection::ConnectionStatus::Disconnected) { @@ -308,7 +320,15 @@ async fn disconnect_bluetooth(mac_address: MacAddr6) -> Result<()> { .context("BlueZ could not disconnect the earbuds") } -fn read_snapshot(device: &dyn OpenSCQ30Device) -> DeviceSnapshot { +/// Daily and button settings are the only `DeviceCommand`s that write arbitrary setting ids. +fn is_control_write(command: &DeviceCommand) -> bool { + matches!( + command, + DeviceCommand::SetToggle(..) | DeviceCommand::SetSelect { .. } + ) +} + +fn read_snapshot(device: &dyn OpenSCQ30Device, read_only_controls: bool) -> DeviceSnapshot { for setting_id in [ SettingId::BatteryLevelLeft, SettingId::BatteryLevelRight, @@ -321,7 +341,12 @@ fn read_snapshot(device: &dyn OpenSCQ30Device) -> DeviceSnapshot { ] { tracing::debug!(?setting_id, setting = ?device.setting(&setting_id), "device setting"); } - snapshot_from_settings(|setting_id: SettingId| device.setting(&setting_id)) + let mut snapshot = snapshot_from_settings(|setting_id: SettingId| device.setting(&setting_id)); + if read_only_controls { + snapshot.daily_controls.clear(); + snapshot.button_controls.clear(); + } + snapshot } fn database_path() -> Result { diff --git a/src/devices.rs b/src/devices.rs index ceb2e76..436c693 100644 --- a/src/devices.rs +++ b/src/devices.rs @@ -22,6 +22,11 @@ pub struct DeviceProfile { /// settings manager doesn't register, rather than returning an error. Defaults to /// `false` (skip the repair) for any unverified model. pub supports_manual_ambient_ranges: bool, + /// Experimental/aliased models whose daily and button controls cannot be trusted + /// (the state packet layout only partly matches the `openscq30-lib` model they are + /// mapped to). Those controls are hidden and their writes are dropped, so only + /// battery, ambient and equalizer are exposed. Defaults to `false`. + pub read_only_controls: bool, } #[derive(Debug, Deserialize)] @@ -36,6 +41,8 @@ struct RawDeviceProfile { display_name: String, icon: Option, supports_manual_ambient_ranges: bool, + #[serde(default)] + read_only_controls: bool, } /// Device icon PNGs, named in `assets/devices.toml`'s `icon` field. @@ -75,6 +82,7 @@ fn load_device_profiles() -> Vec { display_name: raw.display_name, icon, supports_manual_ambient_ranges: raw.supports_manual_ambient_ranges, + read_only_controls: raw.read_only_controls, } }) .collect() @@ -122,9 +130,16 @@ mod tests { } } + fn liberty_4_pro() -> &'static DeviceProfile { + DEVICE_PROFILES + .iter() + .find(|profile| profile.display_name == "Liberty 4 Pro") + .expect("Liberty 4 Pro is registered") + } + #[test] fn matches_by_name_case_insensitively() { - let profile = &DEVICE_PROFILES[0]; + let profile = liberty_4_pro(); let descriptors = vec![descriptor("SOUNDCORE LIBERTY 4 PRO", "AA:BB:CC:DD:EE:FF")]; let found = find_matching_descriptor(&descriptors, profile, None); @@ -134,7 +149,7 @@ mod tests { #[test] fn ignores_name_when_mac_is_configured() { - let profile = &DEVICE_PROFILES[0]; + let profile = liberty_4_pro(); let configured_mac = "11:22:33:44:55:66".parse().unwrap(); let descriptors = vec![ descriptor("soundcore Liberty 4 Pro", "AA:BB:CC:DD:EE:FF"), @@ -148,7 +163,7 @@ mod tests { #[test] fn returns_none_when_nothing_matches() { - let profile = &DEVICE_PROFILES[0]; + let profile = liberty_4_pro(); let descriptors = vec![descriptor("unrelated device", "AA:BB:CC:DD:EE:FF")]; assert_eq!(find_matching_descriptor(&descriptors, profile, None), None); @@ -167,7 +182,12 @@ mod tests { #[test] fn loads_icons_for_every_registered_profile() { - for profile in DEVICE_PROFILES.iter() { + // Experimental read-only aliases (e.g. K20i) have no artwork of their own and use + // the generic placeholder rather than another product's picture. + for profile in DEVICE_PROFILES + .iter() + .filter(|profile| !profile.read_only_controls) + { assert!( profile.icon.is_some(), "{} should have an icon key wired up", diff --git a/src/domain.rs b/src/domain.rs index b408695..34f3c50 100644 --- a/src/domain.rs +++ b/src/domain.rs @@ -24,6 +24,9 @@ pub struct EqualizerState { pub min: i16, pub max: i16, pub fraction_digits: i16, + /// The device only accepts preset selection (no custom per-band gains), so the bands + /// are shown but cannot be edited. + pub read_only: bool, } #[derive(Clone, Debug, PartialEq)] @@ -320,12 +323,17 @@ fn select_options(setting: openscq30_lib::settings::Select) -> Vec fn equalizer_state(setting: Setting) -> Option { match setting { - Setting::Equalizer { setting, value, .. } => Some(EqualizerState { + Setting::Equalizer { + setting, + value, + read_only, + } => Some(EqualizerState { frequencies_hz: setting.band_hz.into_owned(), gains: value, min: setting.min, max: setting.max, fraction_digits: setting.fraction_digits, + read_only, }), _ => None, } diff --git a/src/ui/equalizer.rs b/src/ui/equalizer.rs index 8f9683e..8e41604 100644 --- a/src/ui/equalizer.rs +++ b/src/ui/equalizer.rs @@ -37,6 +37,7 @@ impl SoundcoreApp { let connected = self.is_connected(); let mut changed_gains = None; if let Some(equalizer) = &mut self.snapshot.equalizer { + let editable = connected && !equalizer.read_only; let mut changed = false; let band_count = equalizer.gains.len().max(1) as f32; let band_width = (ui.available_width() / band_count).max(34.0); @@ -54,7 +55,7 @@ impl SoundcoreApp { RichText::new(format!("{db:+.1}")).size(11.0).color(MUTED), ); let response = ui.add_enabled( - connected, + editable, egui::Slider::new(gain, equalizer.min..=equalizer.max) .vertical() .show_value(false), @@ -71,12 +72,25 @@ impl SoundcoreApp { ); } }); + if equalizer.read_only { + ui.add_space(8.0); + ui.label( + RichText::new("These earbuds only support the presets above.") + .size(12.0) + .color(MUTED), + ); + } if changed { changed_gains = Some(equalizer.gains.clone()); } } else { + // Some models hide the equalizer until both earbuds are connected. ui.label( - RichText::new("Equalizer data will appear after connection.").color(MUTED), + RichText::new( + "The equalizer is not available yet. Some earbuds need both buds \ + connected.", + ) + .color(MUTED), ); ui.add_space(72.0); } diff --git a/tests/domain_test.rs b/tests/domain_test.rs index 48d2527..251595b 100644 --- a/tests/domain_test.rs +++ b/tests/domain_test.rs @@ -230,3 +230,28 @@ fn missing_settings_produce_safe_defaults() { assert_eq!(snapshot, Default::default()); } + +#[test] +fn equalizer_state_carries_the_read_only_flag() { + let equalizer = |read_only| { + HashMap::from([( + SettingId::VolumeAdjustments, + Setting::Equalizer { + setting: Equalizer { + band_hz: Cow::Borrowed(&[100, 200, 400, 800, 1600, 3200, 6400, 12800]), + fraction_digits: 1, + min: -120, + max: 134, + }, + read_only, + value: vec![0; 8], + }, + )]) + }; + + let editable = snapshot_from_settings(|id| equalizer(false).get(&id).cloned()); + let preset_only = snapshot_from_settings(|id| equalizer(true).get(&id).cloned()); + + assert!(!editable.equalizer.unwrap().read_only); + assert!(preset_only.equalizer.unwrap().read_only); +}