Donate to e Foundation | Murena handsets with /e/OS | Own a part of Murena! Learn more

Commit 60b70d24 authored by Hsin-chen Chuang's avatar Hsin-chen Chuang
Browse files

floss mgmt: Fix clippy warnings

- warning: this `MutexGuard` is held across an `await` point
- warning: you seem to be trying to use `match` for destructuring a
           single pattern. Consider using `if let`
- warning: methods with the following characteristics: (`to_*` and
           `self` type is `Copy`) usually take `self` by value
- warning: match expression looks like `matches!` macro
- warning: use of `format!` to build up a string from an iterator
- warning: in a `match` scrutinee, avoid complex blocks or closures with
           blocks; instead, move the block or closure higher and bind it
           with a `let`
- warning: you seem to want to iterate on a map's values

Bug: 343315863
Tag: #floss
Test: mmm packages/modules/Bluetooth
Test: ./build.py --target test
Flag: EXEMPT, Floss-only changes
Change-Id: Ief38ba9b870d952e52f8d8099c480c25bb03a67c
parent efe7e97c
Loading
Loading
Loading
Loading
+6 −11
Original line number Diff line number Diff line
@@ -51,7 +51,7 @@ impl BluetoothManager {
        } else {
            warn!("Presence removed: {}", hci);
        }
        for (_, callback) in &mut self.callbacks {
        for callback in self.callbacks.values_mut() {
            callback.on_hci_device_changed(hci.to_i32(), present);
        }
    }
@@ -63,13 +63,13 @@ impl BluetoothManager {
            warn!("Stopped {}", hci);
        }

        for (_, callback) in &mut self.callbacks {
        for callback in self.callbacks.values_mut() {
            callback.on_hci_enabled_changed(hci.to_i32(), enabled);
        }
    }

    pub(crate) fn callback_default_adapter_change(&mut self, hci: VirtualHciIndex) {
        for (_, callback) in &mut self.callbacks {
        for callback in self.callbacks.values_mut() {
            callback.on_default_adapter_changed(hci.to_i32());
        }
    }
@@ -272,14 +272,9 @@ fn floss_have_le_devices() -> bool {
impl IBluetoothExperimental for BluetoothManager {
    fn set_ll_privacy(&mut self, enabled: bool) -> bool {
        warn!("Set Floss LL Privacy={}", enabled);
        let current_status = match config_util::read_floss_ll_privacy_enabled() {
            Ok(true) => true,
            _ => false,
        };
        let current_address_status = match config_util::read_floss_address_privacy_enabled() {
            Ok(true) => true,
            _ => false,
        };
        let current_status = matches!(config_util::read_floss_ll_privacy_enabled(), Ok(true));
        let current_address_status =
            matches!(config_util::read_floss_address_privacy_enabled(), Ok(true));

        let mut need_restart = current_status != enabled;

+8 −8
Original line number Diff line number Diff line
@@ -143,14 +143,14 @@ pub fn get_default_adapter() -> VirtualHciIndex {
}

pub fn set_default_adapter(hci: VirtualHciIndex) -> bool {
    match read_config().ok().and_then(|config| {
        let mut cfg = serde_json::from_str::<Value>(config.as_str()).ok()?;
        cfg[DEFAULT_ADAPTER_KEY] = serde_json::to_value(hci.to_i32()).ok().unwrap();
        serde_json::ser::to_string_pretty(&cfg).ok()
    }) {
        Some(s) => std::fs::write(BTMANAGERD_CONF, s).is_ok(),
        None => false,
    }
    (|| {
        let config: String = read_config()?;
        let mut cfg = serde_json::from_str::<Value>(config.as_str())?;
        cfg[DEFAULT_ADAPTER_KEY] = serde_json::to_value(hci.to_i32())?;
        let new_config: String = serde_json::ser::to_string_pretty(&cfg)?;
        std::fs::write(BTMANAGERD_CONF, new_config)
    })()
    .is_ok()
}

fn list_hci_devices_string() -> Vec<String> {
+3 −2
Original line number Diff line number Diff line
@@ -110,8 +110,9 @@ pub async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let bluetooth_manager = Arc::new(Mutex::new(Box::new(BluetoothManager::new(proxy))));

    // Set up the disconnect watcher to monitor client disconnects.
    let disconnect_watcher = Arc::new(Mutex::new(DisconnectWatcher::new()));
    disconnect_watcher.lock().unwrap().setup_watch(conn.clone()).await;
    let mut disconnect_watcher = DisconnectWatcher::new();
    disconnect_watcher.setup_watch(conn.clone()).await;
    let disconnect_watcher = Arc::new(Mutex::new(disconnect_watcher));

    // We add the Crossroads instance to the connection so that incoming method calls will be
    // handled.
+22 −27
Original line number Diff line number Diff line
@@ -11,6 +11,7 @@
//!   all others

use std::collections::HashMap;
use std::fmt::Write;
use std::fs;
use std::path::Path;

@@ -242,7 +243,10 @@ fn dec_str_to_hex_str(str: String) -> Result<String, String> {
fn base64_str_to_hex_str(str: String) -> Result<String, String> {
    match base64::decode(str) {
        Ok(bytes) => {
            let res: String = bytes.iter().map(|b| format!("{:02x}", b)).collect();
            let res: String = bytes.iter().fold(String::new(), |mut res, b| {
                let _ = write!(res, "{:02x}", b);
                res
            });
            Ok(res)
        }
        Err(err) => Err(format!("Error converting from base64 string to hex string: {}", err)),
@@ -616,9 +620,8 @@ pub fn migrate_bluez_devices() {
fn merge_and_write_bluez_conf(filepath: String, conf: &mut Ini) {
    let mut existing_conf = Ini::new_cs();
    existing_conf.set_comment_symbols(&['!', '#']);
    match existing_conf.load(filepath.clone()) {
    if let Ok(ini) = existing_conf.load(filepath.clone()) {
        // Device already exists in BlueZ
        Ok(ini) => {
        for (sec, props) in ini {
            // Keep keys that weren't transferrable
            for (k, v) in props {
@@ -628,8 +631,6 @@ fn merge_and_write_bluez_conf(filepath: String, conf: &mut Ini) {
            }
        }
    }
        Err(_) => {}
    }
    // Write BlueZ file
    match conf.write(filepath.clone()) {
        Ok(_) => {
@@ -880,16 +881,13 @@ fn convert_floss_conf(filename: &str) {
    }

    // Delete devices that exist in BlueZ but not in Floss
    match glob(format!("{}/{}/*:*", BT_LIBDIR, adapter_addr).as_str()) {
        Ok(globbed) => {
    if let Ok(globbed) = glob(format!("{}/{}/*:*", BT_LIBDIR, adapter_addr).as_str()) {
        for entry in globbed {
            let pathbuf = entry.unwrap_or_default();
            let addrs = pathbuf.to_str().unwrap_or_default().split('/').collect::<Vec<&str>>();
            let device_addr: String = addrs[addrs.len() - 1].into();
            if !devices.contains(&device_addr.to_lowercase()) {
                    match fs::remove_dir_all(pathbuf) {
                        Ok(_) => (),
                        Err(err) => {
                if let Err(err) = fs::remove_dir_all(pathbuf) {
                    warn!(
                        "Error removing {} during Floss to BlueZ device migration: {}",
                        device_addr, err
@@ -899,9 +897,6 @@ fn convert_floss_conf(filename: &str) {
        }
    }
}
        _ => (),
    }
}

/// This is the main function that handles the device migration from Floss to BlueZ.
pub fn migrate_floss_devices() {
+6 −12
Original line number Diff line number Diff line
@@ -54,10 +54,7 @@ pub enum ProcessState {

/// Check whether adapter is enabled by checking internal state.
pub fn state_to_enabled(state: ProcessState) -> bool {
    match state {
        ProcessState::On | ProcessState::TurningOff => true,
        _ => false,
    }
    matches!(state, ProcessState::On | ProcessState::TurningOff)
}

/// Device path of hci device in sysfs. This will uniquely identify a Bluetooth
@@ -73,7 +70,7 @@ pub const INVALID_HCI_INDEX: i32 = -1;
#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub struct VirtualHciIndex(pub i32);
impl VirtualHciIndex {
    pub(crate) fn to_i32(&self) -> i32 {
    pub(crate) fn to_i32(self) -> i32 {
        self.0
    }
}
@@ -87,7 +84,7 @@ impl Display for VirtualHciIndex {
#[derive(Clone, Copy, Debug, PartialEq, PartialOrd)]
pub struct RealHciIndex(pub i32);
impl RealHciIndex {
    pub(crate) fn to_i32(&self) -> i32 {
    pub(crate) fn to_i32(self) -> i32 {
        self.0
    }
}
@@ -850,19 +847,16 @@ pub async fn mainloop(
                                    }
                                }
                            });
                            match context
                            if let Some(handle) = context
                                .state_machine
                                .process_monitor
                                .lock()
                                .unwrap()
                                .insert(fname.clone(), handle)
                            {
                                Some(handle) => {
                                warn!("{}: Aborting old handler", hci);
                                handle.abort();
                            }
                                None => {}
                            }
                        }
                        _ => debug!("Invalid pid path: {}", fname),
                    }