Skip to main content

btleplug/bluez/
peripheral.rs

1use async_trait::async_trait;
2use bluez_async::{
3    BluetoothEvent, BluetoothSession, CharacteristicEvent, CharacteristicFlags, CharacteristicId,
4    CharacteristicInfo, DescriptorInfo, DeviceId, DeviceInfo, MacAddress, ServiceInfo,
5    WriteOptions,
6};
7use futures::future::{join_all, ready};
8use futures::stream::{Stream, StreamExt};
9#[cfg(feature = "serde")]
10use serde::{Deserialize, Serialize};
11#[cfg(feature = "serde")]
12use serde_cr as serde;
13use std::collections::{BTreeSet, HashMap};
14use std::fmt::{self, Display, Formatter};
15use std::pin::Pin;
16use std::sync::{Arc, Mutex};
17use uuid::Uuid;
18
19use crate::api::{
20    self, AddressType, BDAddr, CharPropFlags, Characteristic, Descriptor, PeripheralProperties,
21    Service, ValueNotification, WriteType,
22};
23use crate::{Error, Result};
24
25#[derive(Clone, Debug)]
26struct CharacteristicInternal {
27    info: CharacteristicInfo,
28    descriptors: HashMap<Uuid, DescriptorInfo>,
29}
30
31impl CharacteristicInternal {
32    fn new(info: CharacteristicInfo, descriptors: HashMap<Uuid, DescriptorInfo>) -> Self {
33        Self { info, descriptors }
34    }
35}
36
37#[derive(Clone, Debug)]
38struct ServiceInternal {
39    info: ServiceInfo,
40    characteristics: HashMap<Uuid, CharacteristicInternal>,
41}
42
43#[cfg_attr(
44    feature = "serde",
45    derive(Serialize, Deserialize),
46    serde(crate = "serde_cr")
47)]
48#[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
49pub struct PeripheralId(pub(crate) DeviceId);
50
51impl Display for PeripheralId {
52    fn fmt(&self, f: &mut Formatter) -> fmt::Result {
53        self.0.fmt(f)
54    }
55}
56
57/// Implementation of [api::Peripheral](crate::api::Peripheral).
58#[derive(Clone, Debug)]
59pub struct Peripheral {
60    session: BluetoothSession,
61    device: DeviceId,
62    mac_address: BDAddr,
63    services: Arc<Mutex<HashMap<Uuid, ServiceInternal>>>,
64}
65
66fn get_characteristic<'a>(
67    services: &'a HashMap<Uuid, ServiceInternal>,
68    service_uuid: &Uuid,
69    characteristic_uuid: &Uuid,
70) -> Result<&'a CharacteristicInternal> {
71    services
72        .get(service_uuid)
73        .ok_or_else(|| {
74            Error::Other(format!("Service with UUID {} not found.", service_uuid).into())
75        })?
76        .characteristics
77        .get(characteristic_uuid)
78        .ok_or_else(|| {
79            Error::Other(
80                format!(
81                    "Characteristic with UUID {} not found.",
82                    characteristic_uuid
83                )
84                .into(),
85            )
86        })
87}
88
89impl Peripheral {
90    pub(crate) fn new(session: BluetoothSession, device: DeviceInfo) -> Self {
91        Peripheral {
92            session,
93            device: device.id,
94            mac_address: device.mac_address.into(),
95            services: Arc::new(Mutex::new(HashMap::new())),
96        }
97    }
98
99    fn characteristic_info(&self, characteristic: &Characteristic) -> Result<CharacteristicInfo> {
100        let services = self.services.lock().map_err(Into::<Error>::into)?;
101        get_characteristic(
102            &services,
103            &characteristic.service_uuid,
104            &characteristic.uuid,
105        )
106        .map(|c| &c.info)
107        .cloned()
108    }
109
110    fn descriptor_info(&self, descriptor: &Descriptor) -> Result<DescriptorInfo> {
111        let services = self.services.lock().map_err(Into::<Error>::into)?;
112        let characteristic = get_characteristic(
113            &services,
114            &descriptor.service_uuid,
115            &descriptor.characteristic_uuid,
116        )?;
117        characteristic
118            .descriptors
119            .get(&descriptor.uuid)
120            .ok_or_else(|| {
121                Error::Other(format!("Descriptor with UUID {} not found.", descriptor.uuid).into())
122            })
123            .cloned()
124    }
125
126    async fn device_info(&self) -> Result<DeviceInfo> {
127        Ok(self.session.get_device_info(&self.device).await?)
128    }
129}
130
131#[async_trait]
132impl api::Peripheral for Peripheral {
133    fn id(&self) -> PeripheralId {
134        PeripheralId(self.device.to_owned())
135    }
136
137    fn address(&self) -> BDAddr {
138        self.mac_address
139    }
140
141    fn mtu(&self) -> u16 {
142        let services = self.services.lock().unwrap();
143        for service in services.values() {
144            if let Some((_, characteristic)) = service.characteristics.iter().next() {
145                return characteristic.info.mtu.unwrap();
146            }
147        }
148
149        api::DEFAULT_MTU_SIZE
150    }
151
152    async fn properties(&self) -> Result<Option<PeripheralProperties>> {
153        let device_info = self.device_info().await?;
154        Ok(Some(PeripheralProperties {
155            address: device_info.mac_address.into(),
156            address_type: Some(device_info.address_type.into()),
157            local_name: device_info.alias.or(device_info.name.clone()),
158            advertisement_name: device_info.name,
159            appearance: device_info.appearance,
160            tx_power_level: device_info.tx_power,
161            rssi: device_info.rssi,
162            manufacturer_data: device_info.manufacturer_data,
163            service_data: device_info.service_data,
164            services: device_info.services,
165            class: device_info.class,
166        }))
167    }
168
169    fn services(&self) -> BTreeSet<Service> {
170        self.services
171            .lock()
172            .unwrap()
173            .values()
174            .map(|service| service.into())
175            .collect()
176    }
177
178    async fn is_connected(&self) -> Result<bool> {
179        let device_info = self.device_info().await?;
180        Ok(device_info.connected)
181    }
182
183    async fn connect(&self) -> Result<()> {
184        self.session.connect(&self.device).await?;
185        Ok(())
186    }
187
188    async fn disconnect(&self) -> Result<()> {
189        self.session.disconnect(&self.device).await?;
190        Ok(())
191    }
192
193    async fn discover_services(&self) -> Result<()> {
194        let mut services_internal = HashMap::new();
195        let services = self.session.get_services(&self.device).await?;
196        for service in services {
197            let characteristics = self.session.get_characteristics(&service.id).await?;
198            let characteristics = join_all(
199                characteristics
200                    .into_iter()
201                    .fold(
202                        // Only consider the first characteristic of each UUID
203                        // This "should" be unique, but of course it's not enforced
204                        HashMap::<Uuid, CharacteristicInfo>::new(),
205                        |mut map, characteristic| {
206                            map.entry(characteristic.uuid).or_insert(characteristic);
207                            map
208                        },
209                    )
210                    .into_iter()
211                    .map(|mapped_characteristic| async {
212                        let characteristic = mapped_characteristic.1;
213                        let descriptors = self
214                            .session
215                            .get_descriptors(&characteristic.id)
216                            .await
217                            .unwrap_or(Vec::new())
218                            .into_iter()
219                            .map(|descriptor| (descriptor.uuid, descriptor))
220                            .collect();
221                        CharacteristicInternal::new(characteristic, descriptors)
222                    }),
223            )
224            .await;
225            services_internal.insert(
226                service.uuid,
227                ServiceInternal {
228                    info: service,
229                    characteristics: characteristics
230                        .into_iter()
231                        .map(|characteristic| (characteristic.info.uuid, characteristic))
232                        .collect(),
233                },
234            );
235        }
236        *(self.services.lock().map_err(Into::<Error>::into)?) = services_internal;
237        Ok(())
238    }
239
240    async fn write(
241        &self,
242        characteristic: &Characteristic,
243        data: &[u8],
244        write_type: WriteType,
245    ) -> Result<()> {
246        let characteristic_info = self.characteristic_info(characteristic)?;
247        let options = WriteOptions {
248            write_type: Some(write_type.into()),
249            ..Default::default()
250        };
251        Ok(self
252            .session
253            .write_characteristic_value_with_options(&characteristic_info.id, data, options)
254            .await?)
255    }
256
257    async fn read(&self, characteristic: &Characteristic) -> Result<Vec<u8>> {
258        let characteristic_info = self.characteristic_info(characteristic)?;
259        Ok(self
260            .session
261            .read_characteristic_value(&characteristic_info.id)
262            .await?)
263    }
264
265    async fn subscribe(&self, characteristic: &Characteristic) -> Result<()> {
266        let characteristic_info = self.characteristic_info(characteristic)?;
267        Ok(self.session.start_notify(&characteristic_info.id).await?)
268    }
269
270    async fn unsubscribe(&self, characteristic: &Characteristic) -> Result<()> {
271        let characteristic_info = self.characteristic_info(characteristic)?;
272        Ok(self.session.stop_notify(&characteristic_info.id).await?)
273    }
274
275    async fn notifications(&self) -> Result<Pin<Box<dyn Stream<Item = ValueNotification> + Send>>> {
276        let device_id = self.device.clone();
277        let events = self.session.device_event_stream(&device_id).await?;
278        let services = self.services.clone();
279        Ok(Box::pin(events.filter_map(move |event| {
280            ready(value_notification(event, &device_id, services.clone()))
281        })))
282    }
283
284    async fn read_rssi(&self) -> Result<i16> {
285        let device_info = self.device_info().await?;
286        device_info.rssi.ok_or(Error::NotConnected)
287    }
288
289    async fn write_descriptor(&self, descriptor: &Descriptor, data: &[u8]) -> Result<()> {
290        let descriptor_info = self.descriptor_info(descriptor)?;
291        Ok(self
292            .session
293            .write_descriptor_value(&descriptor_info.id, data)
294            .await?)
295    }
296
297    async fn read_descriptor(&self, descriptor: &Descriptor) -> Result<Vec<u8>> {
298        let descriptor_info = self.descriptor_info(descriptor)?;
299        Ok(self
300            .session
301            .read_descriptor_value(&descriptor_info.id)
302            .await?)
303    }
304}
305
306fn value_notification(
307    event: BluetoothEvent,
308    device_id: &DeviceId,
309    services: Arc<Mutex<HashMap<Uuid, ServiceInternal>>>,
310) -> Option<ValueNotification> {
311    match event {
312        BluetoothEvent::Characteristic {
313            id,
314            event: CharacteristicEvent::Value { value },
315        } if id.service().device() == *device_id => {
316            let services = services.lock().unwrap();
317            let (charac, service) = find_characteristic_by_id(&services, id.clone())?;
318            Some(ValueNotification {
319                uuid: charac.uuid,
320                service_uuid: service.uuid,
321                value,
322            })
323        }
324        _ => None,
325    }
326}
327
328fn find_characteristic_by_id(
329    services: &HashMap<Uuid, ServiceInternal>,
330    characteristic_id: CharacteristicId,
331) -> Option<(&CharacteristicInfo, &ServiceInfo)> {
332    for service in services.values() {
333        for characteristic in service.characteristics.values() {
334            if characteristic.info.id == characteristic_id {
335                return Some((&characteristic.info, &service.info));
336            }
337        }
338    }
339    None
340}
341
342impl From<WriteType> for bluez_async::WriteType {
343    fn from(write_type: WriteType) -> Self {
344        match write_type {
345            WriteType::WithoutResponse => bluez_async::WriteType::WithoutResponse,
346            WriteType::WithResponse => bluez_async::WriteType::WithResponse,
347        }
348    }
349}
350
351impl From<MacAddress> for BDAddr {
352    fn from(mac_address: MacAddress) -> Self {
353        <[u8; 6]>::into(mac_address.into())
354    }
355}
356
357impl From<DeviceId> for PeripheralId {
358    fn from(device_id: DeviceId) -> Self {
359        PeripheralId(device_id)
360    }
361}
362
363impl From<bluez_async::AddressType> for AddressType {
364    fn from(address_type: bluez_async::AddressType) -> Self {
365        match address_type {
366            bluez_async::AddressType::Public => AddressType::Public,
367            bluez_async::AddressType::Random => AddressType::Random,
368        }
369    }
370}
371
372fn make_descriptor(
373    info: &DescriptorInfo,
374    characteristic_uuid: Uuid,
375    service_uuid: Uuid,
376) -> Descriptor {
377    Descriptor {
378        uuid: info.uuid,
379        characteristic_uuid,
380        service_uuid,
381    }
382}
383
384fn make_characteristic(
385    characteristic: &CharacteristicInternal,
386    service_uuid: Uuid,
387) -> Characteristic {
388    let CharacteristicInternal { info, descriptors } = characteristic;
389    Characteristic {
390        uuid: info.uuid,
391        properties: info.flags.into(),
392        descriptors: descriptors
393            .values()
394            .map(|descriptor| make_descriptor(descriptor, info.uuid, service_uuid))
395            .collect(),
396        service_uuid,
397    }
398}
399
400impl From<&ServiceInternal> for Service {
401    fn from(service: &ServiceInternal) -> Self {
402        Service {
403            uuid: service.info.uuid,
404            primary: service.info.primary,
405            characteristics: service
406                .characteristics
407                .values()
408                .map(|characteristic| make_characteristic(characteristic, service.info.uuid))
409                .collect(),
410        }
411    }
412}
413
414impl From<CharacteristicFlags> for CharPropFlags {
415    fn from(flags: CharacteristicFlags) -> Self {
416        let mut result = CharPropFlags::default();
417        if flags.contains(CharacteristicFlags::BROADCAST) {
418            result.insert(CharPropFlags::BROADCAST);
419        }
420        if flags.contains(CharacteristicFlags::READ) {
421            result.insert(CharPropFlags::READ);
422        }
423        if flags.contains(CharacteristicFlags::WRITE_WITHOUT_RESPONSE) {
424            result.insert(CharPropFlags::WRITE_WITHOUT_RESPONSE);
425        }
426        if flags.contains(CharacteristicFlags::WRITE) {
427            result.insert(CharPropFlags::WRITE);
428        }
429        if flags.contains(CharacteristicFlags::NOTIFY) {
430            result.insert(CharPropFlags::NOTIFY);
431        }
432        if flags.contains(CharacteristicFlags::INDICATE) {
433            result.insert(CharPropFlags::INDICATE);
434        }
435        if flags.contains(CharacteristicFlags::SIGNED_WRITE) {
436            result.insert(CharPropFlags::AUTHENTICATED_SIGNED_WRITES);
437        }
438        if flags.contains(CharacteristicFlags::EXTENDED_PROPERTIES) {
439            result.insert(CharPropFlags::EXTENDED_PROPERTIES);
440        }
441        result
442    }
443}