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

Commit b0903dbf authored by Sonny Sasaka's avatar Sonny Sasaka
Browse files

Cleanup floss code

This cleans up compiler warnings and removes unused binary in "adapter"
crate.

Bug: 186492781
Tag: #floss
Test: manual - build on Linux and Chrome OS

Change-Id: I0ecc7c525e3403cc68180198bd19e78e2a2df4b5
parent e065d9ac
Loading
Loading
Loading
Loading
+0 −1
Original line number Diff line number Diff line
@@ -19,6 +19,5 @@ members = [
  "gd/rust/shim",
  "gd/rust/topshim",
  "gd/rust/linux/mgmt",
  "gd/rust/linux/adapter",
  "gd/rust/linux/service",
]
+0 −37
Original line number Diff line number Diff line
#
#  Copyright 2021 Google, Inc.
#
#  Licensed under the Apache License, Version 2.0 (the "License");
#  you may not use this file except in compliance with the License.
#  You may obtain a copy of the License at:
#
#  http://www.apache.org/licenses/LICENSE-2.0
#
#  Unless required by applicable law or agreed to in writing, software
#  distributed under the License is distributed on an "AS IS" BASIS,
#  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#  See the License for the specific language governing permissions and
#  limitations under the License.

[package]
name = "bluetooth"
version = "0.0.1"
edition = "2018"

[dependencies]
# BT dependencies
bt_topshim = { path = "../../topshim" }
bt_shim = { path = "../../shim" }

num-traits = "*"
num-derive = "*"
tokio = { version = "1.0", features = ['bytes', 'fs', 'io-util', 'libc', 'macros', 'memchr', 'mio', 'net', 'num_cpus', 'rt', 'rt-multi-thread', 'sync', 'time', 'tokio-macros'] }
tokio-stream = "0.1"

[build-dependencies]
pkg-config = "0.3"

[[bin]]
name = "bluetoothd"
path = "src/main.rs"
build = "build.rs"
+0 −25
Original line number Diff line number Diff line
use pkg_config::Config;

fn main() {
    // The main linking point with c++ code is the libbluetooth-static.a
    // These includes all the symbols built via C++ but doesn't include other
    // links (i.e. pkg-config)
    println!("cargo:rustc-link-lib=static=bluetooth-static");

    // A few dynamic links
    println!("cargo:rustc-link-lib=dylib=flatbuffers");
    println!("cargo:rustc-link-lib=dylib=protobuf");
    println!("cargo:rustc-link-lib=dylib=resolv");

    // Clang requires -lc++ instead of -lstdc++
    println!("cargo:rustc-link-lib=c++");

    // A few more dependencies from pkg-config. These aren't included as part of
    // the libbluetooth-static.a
    Config::new().probe("libchrome").unwrap();
    Config::new().probe("libmodp_b64").unwrap();
    Config::new().probe("tinyxml2").unwrap();

    println!("cargo:rerun-if-changed=build.rs");
    println!("cargo:rerun-if-changed=libbluetooth-static.a");
}
+0 −130
Original line number Diff line number Diff line
use bt_topshim::btif;
use bt_topshim::btif::{BaseCallbacks, BaseCallbacksDispatcher, BluetoothInterface};
use bt_topshim::topstack;
use num_traits::{FromPrimitive, ToPrimitive};
use std::convert::TryFrom;
use std::env;
use std::time::Duration;
use tokio::sync::mpsc;
use tokio::sync::mpsc::{Receiver, Sender};
use tokio::time::sleep;

// DO NOT REMOVE
// Required so that bt_shim is linked into the final image
extern crate bt_shim;

struct Context {
    tx: Sender<BaseCallbacks>,
    rx: Receiver<BaseCallbacks>,
    dispatcher: Option<BaseCallbacksDispatcher>,
    intf: BluetoothInterface,
}

fn make_context(intf: BluetoothInterface) -> Context {
    let (tx, rx) = mpsc::channel::<BaseCallbacks>(1);

    let tx1 = tx.clone();
    let dispatcher = btif::BaseCallbacksDispatcher {
        dispatch: Box::new(move |cb| {
            let txl = tx1.clone();
            topstack::get_runtime().spawn(async move {
                txl.send(cb).await;
            });
        }),
    };

    return Context { tx, rx, dispatcher: Some(dispatcher), intf };
}

async fn mainloop(context: &mut Context) {
    'main: while let Some(cb) = context.rx.recv().await {
        match cb {
            BaseCallbacks::AdapterState(state) => {
                println!("Adapter state changed to {}", state.to_u32().unwrap());

                if state == btif::BtState::On {
                    context.intf.get_adapter_properties();
                }
            }
            BaseCallbacks::AdapterProperties(status, _count, properties) => {
                if status != btif::BtStatus::Success {
                    println!("Failed property change: {:?}", status);
                }

                for p in properties {
                    println!("Property {:?} is ({:?})", p.prop_type, p.val);
                }

                // Scan for 5s and then cancel
                println!("Starting discovery");
                context.intf.start_discovery();
            }
            BaseCallbacks::RemoteDeviceProperties(status, address, _count, properties) => {
                if status != btif::BtStatus::Success {
                    println!("Failed remote property change: {:?}", status);
                }

                println!("Properties for {:?}", address.address);

                for p in properties {
                    println!("Property {:?} is ({:?})", p.prop_type, p.val);
                }
            }
            BaseCallbacks::DeviceFound(_count, properties) => {
                print!("Device found: ");

                for p in properties {
                    if p.prop_type == btif::BtPropertyType::BdAddr {
                        print!(" Addr[{:?}]", p.val);
                    } else if p.prop_type == btif::BtPropertyType::BdName {
                        print!(
                            " Name[{:?}]",
                            p.val.iter().map(|u| char::try_from(*u).unwrap()).collect::<String>()
                        );
                    }
                }

                println!("");
            }
            BaseCallbacks::DiscoveryState(state) => {
                if state == btif::BtDiscoveryState::Started {
                    sleep(Duration::from_millis(5000)).await;
                    context.intf.cancel_discovery();

                    break 'main;
                }
            }
            _ => println!("{:?}", cb),
        }
    }
}

fn main() {
    println!("Bluetooth Adapter Daemon");

    // Drop the first arg (which is the binary name)
    let all_args: Vec<String> = env::args().collect();
    let args = all_args[1..].to_vec();

    let intf = btif::get_btinterface().expect("Couldn't get bluetooth interface");
    let mut context = make_context(intf);

    topstack::get_runtime().block_on(async move {
        if let Some(dispatcher) = context.dispatcher {
            if !context.intf.initialize(dispatcher, args) {
                panic!("Couldn't initialize bluetooth interface!");
            }

            context.dispatcher = None;
        }

        println!("Enabling...");
        context.intf.enable();

        println!("Running mainloop now");
        mainloop(&mut context).await;

        println!("Disabling and exiting...");
        context.intf.disable();
    });
}
+1 −6
Original line number Diff line number Diff line
@@ -5,13 +5,8 @@ use bt_topshim::btif::{
};
use bt_topshim::topstack;

use btif_macros::btif_callbacks_generator;
use btif_macros::stack_message;

use num_traits::cast::ToPrimitive;
use num_traits::FromPrimitive;

use std::fmt::Debug;
use std::sync::Arc;
use std::sync::Mutex;

@@ -99,7 +94,7 @@ pub fn get_bt_dispatcher(tx: Sender<Message>) -> BaseCallbacksDispatcher {
        dispatch: Box::new(move |cb| {
            let txl = tx.clone();
            topstack::get_runtime().spawn(async move {
                txl.send(Message::Base(cb)).await;
                let _ = txl.send(Message::Base(cb)).await;
            });
        }),
    }
Loading