Skip to main content

narwhal_tooth/
lib.rs

1pub mod bluetooth;
2
3use std::time::Duration;
4use std::thread;
5use std::ops::{Deref, DerefMut};
6use async_once::AsyncOnce;
7use btleplug::api::{Central, ScanFilter, Peripheral as _};
8use btleplug::platform::{Adapter, Peripheral};
9use simplelog::{TermLogger, Config};
10use lazy_static::lazy_static;
11use bluetooth::{get_adapter, connect_peripheral, BluetoothConnection, peripheral_by_addr};
12
13lazy_static! {
14    pub static ref CENTRAL: AsyncOnce<Adapter> = AsyncOnce::new(async {
15        get_adapter().await
16    });
17}
18
19pub fn init_logger() {
20    TermLogger::init(log::LevelFilter::Info, Config::default(), simplelog::TerminalMode::Stdout, simplelog::ColorChoice::Auto).unwrap();
21}
22
23pub struct ScanResult {
24    pub result: Vec<Peripheral>,
25}
26
27impl ScanResult {
28    pub async fn get_by_name(&self, name: &str) -> Option<Peripheral> {
29        for device in self.iter() {
30            let props = device.properties().await.unwrap().unwrap();
31            if props.local_name == Some(name.to_string()) {
32                return Some(device.clone());
33            }
34        }
35
36        return None;
37    }
38}
39
40impl Deref for ScanResult {
41    type Target = Vec<Peripheral>;
42    fn deref(&self) -> &Vec<Peripheral> { &self.result }
43}
44
45impl DerefMut for ScanResult {
46    fn deref_mut(&mut self) -> &mut Vec<Peripheral> { &mut self.result }
47}
48
49/// Scan for BLE devices
50pub async fn scan_bluetooth(time: u8) -> ScanResult {
51    CENTRAL.get().await
52        .start_scan(ScanFilter::default())
53        .await
54        .expect("Couldn't scan for BLE devices...");
55
56    thread::sleep(Duration::from_secs(time as u64)); // Wait until the scan is done
57
58    let result = CENTRAL.get().await
59        .peripherals()
60        .await
61        .expect("Couldn't retrieve peripherals from BLE adapter...");
62
63    ScanResult {
64        result
65    }
66}
67
68pub async fn connect_by_address(address: String) -> BluetoothConnection {
69    let peripheral = peripheral_by_addr(&address).await.expect("Failed to find peripheral");
70    connect_peripheral(&peripheral).await.expect("Error")
71}
72
73#[cfg(test)]
74mod test {
75    use crate::{scan_bluetooth, bluetooth::connect_peripheral};
76
77    #[tokio::test]
78    async fn test_ble() {
79        let result = scan_bluetooth(5).await;
80        let hmsoft = result.get_by_name("HMSoft").await.expect("Could not find HMSoft device");
81        let connection = connect_peripheral(&hmsoft).await.unwrap();
82
83        connection.write("on".as_bytes()).await.unwrap();
84        connection.disconnect().await.unwrap();
85    }
86}