1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
use super::peripheral::Peripheral;
use crate::api::{BDAddr, Central, CentralEvent};
use crate::{Error, Result};
use async_trait::async_trait;
use bluez_async::{
    AdapterId, BluetoothError, BluetoothEvent, BluetoothSession, DeviceEvent, DiscoveryFilter,
    Transport,
};
use futures::stream::{self, Stream, StreamExt};
use std::pin::Pin;

/// Implementation of [api::Central](crate::api::Central).
#[derive(Clone, Debug)]
pub struct Adapter {
    session: BluetoothSession,
    adapter: AdapterId,
}

impl Adapter {
    pub(crate) fn new(session: BluetoothSession, adapter: AdapterId) -> Self {
        Self { session, adapter }
    }
}

#[async_trait]
impl Central for Adapter {
    type Peripheral = Peripheral;

    async fn events(&self) -> Result<Pin<Box<dyn Stream<Item = CentralEvent> + Send>>> {
        // There's a race between getting this event stream and getting the current set of devices.
        // Get the stream first, on the basis that it's better to have a duplicate DeviceDiscovered
        // event than to miss one. It's unlikely to happen in any case.
        let events = self.session.event_stream().await?;

        // Synthesise `DeviceDiscovered' events for existing peripherals.
        let devices = self.session.get_devices().await?;
        let initial_events = stream::iter(
            devices
                .into_iter()
                .map(|device| CentralEvent::DeviceDiscovered(BDAddr::from(&device.mac_address))),
        );

        let session = self.session.clone();
        let events = events.filter_map(move |event| central_event(event, session.clone()));

        Ok(Box::pin(initial_events.chain(events)))
    }

    async fn start_scan(&self) -> Result<()> {
        let filter = DiscoveryFilter {
            transport: Some(Transport::Auto),
            ..Default::default()
        };
        self.session.start_discovery_with_filter(&filter).await?;
        Ok(())
    }

    async fn stop_scan(&self) -> Result<()> {
        self.session.stop_discovery().await?;
        Ok(())
    }

    async fn peripherals(&self) -> Result<Vec<Peripheral>> {
        let devices = self.session.get_devices().await?;
        Ok(devices
            .into_iter()
            .map(|device| Peripheral::new(self.session.clone(), device))
            .collect())
    }

    async fn peripheral(&self, address: BDAddr) -> Result<Peripheral> {
        let devices = self.session.get_devices().await?;
        devices
            .into_iter()
            .find_map(|device| {
                if BDAddr::from(&device.mac_address) == address {
                    Some(Peripheral::new(self.session.clone(), device))
                } else {
                    None
                }
            })
            .ok_or(Error::DeviceNotFound)
    }

    async fn add_peripheral(&self, _address: BDAddr) -> Result<Peripheral> {
        Err(Error::NotSupported(
            "Can't add a Peripheral from a BDAddr".to_string(),
        ))
    }
}

impl From<BluetoothError> for Error {
    fn from(error: BluetoothError) -> Self {
        Error::Other(Box::new(error))
    }
}

async fn central_event(event: BluetoothEvent, session: BluetoothSession) -> Option<CentralEvent> {
    match event {
        BluetoothEvent::Device {
            id,
            event: DeviceEvent::Discovered,
        } => {
            let device = session.get_device_info(&id).await.ok()?;
            Some(CentralEvent::DeviceDiscovered((&device.mac_address).into()))
        }
        BluetoothEvent::Device {
            id,
            event: DeviceEvent::Connected { connected },
        } => {
            let device = session.get_device_info(&id).await.ok()?;
            if connected {
                Some(CentralEvent::DeviceConnected((&device.mac_address).into()))
            } else {
                Some(CentralEvent::DeviceDisconnected(
                    (&device.mac_address).into(),
                ))
            }
        }
        BluetoothEvent::Device {
            id,
            event: DeviceEvent::RSSI { rssi: _ },
        } => {
            let device = session.get_device_info(&id).await.ok()?;
            Some(CentralEvent::DeviceUpdated((&device.mac_address).into()))
        }
        BluetoothEvent::Device {
            id,
            event: DeviceEvent::ManufacturerData { manufacturer_data },
        } => {
            let device = session.get_device_info(&id).await.ok()?;
            Some(CentralEvent::ManufacturerDataAdvertisement {
                address: (&device.mac_address).into(),
                manufacturer_data,
            })
        }
        BluetoothEvent::Device {
            id,
            event: DeviceEvent::ServiceData { service_data },
        } => {
            let device = session.get_device_info(&id).await.ok()?;
            Some(CentralEvent::ServiceDataAdvertisement {
                address: (&device.mac_address).into(),
                service_data,
            })
        }
        BluetoothEvent::Device {
            id,
            event: DeviceEvent::Services { services },
        } => {
            let device = session.get_device_info(&id).await.ok()?;
            Some(CentralEvent::ServicesAdvertisement {
                address: (&device.mac_address).into(),
                services,
            })
        }
        _ => None,
    }
}