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#[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().unwrap();
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().unwrap();
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 async fn properties(&self) -> Result<Option<PeripheralProperties>> {
142 let device_info = self.device_info().await?;
143 Ok(Some(PeripheralProperties {
144 address: device_info.mac_address.into(),
145 address_type: Some(device_info.address_type.into()),
146 local_name: device_info.name,
147 tx_power_level: device_info.tx_power,
148 rssi: device_info.rssi,
149 manufacturer_data: device_info.manufacturer_data,
150 service_data: device_info.service_data,
151 services: device_info.services,
152 class: device_info.class,
153 }))
154 }
155
156 fn services(&self) -> BTreeSet<Service> {
157 self.services
158 .lock()
159 .unwrap()
160 .values()
161 .map(|service| service.into())
162 .collect()
163 }
164
165 async fn is_connected(&self) -> Result<bool> {
166 let device_info = self.device_info().await?;
167 Ok(device_info.connected)
168 }
169
170 async fn connect(&self) -> Result<()> {
171 self.session.connect(&self.device).await?;
172 Ok(())
173 }
174
175 async fn disconnect(&self) -> Result<()> {
176 self.session.disconnect(&self.device).await?;
177 Ok(())
178 }
179
180 async fn discover_services(&self) -> Result<()> {
181 let mut services_internal = HashMap::new();
182 let services = self.session.get_services(&self.device).await?;
183 for service in services {
184 let characteristics = self.session.get_characteristics(&service.id).await?;
185 let characteristics =
186 join_all(characteristics.into_iter().map(|characteristic| async {
187 let descriptors = self
188 .session
189 .get_descriptors(&characteristic.id)
190 .await
191 .unwrap_or(Vec::new())
192 .into_iter()
193 .map(|descriptor| (descriptor.uuid, descriptor))
194 .collect();
195 CharacteristicInternal::new(characteristic, descriptors)
196 }))
197 .await;
198 services_internal.insert(
199 service.uuid,
200 ServiceInternal {
201 info: service,
202 characteristics: characteristics
203 .into_iter()
204 .map(|characteristic| (characteristic.info.uuid, characteristic))
205 .collect(),
206 },
207 );
208 }
209 *self.services.lock().unwrap() = services_internal;
210 Ok(())
211 }
212
213 async fn write(
214 &self,
215 characteristic: &Characteristic,
216 data: &[u8],
217 write_type: WriteType,
218 ) -> Result<()> {
219 let characteristic_info = self.characteristic_info(characteristic)?;
220 let options = WriteOptions {
221 write_type: Some(write_type.into()),
222 ..Default::default()
223 };
224 Ok(self
225 .session
226 .write_characteristic_value_with_options(&characteristic_info.id, data, options)
227 .await?)
228 }
229
230 async fn read(&self, characteristic: &Characteristic) -> Result<Vec<u8>> {
231 let characteristic_info = self.characteristic_info(characteristic)?;
232 Ok(self
233 .session
234 .read_characteristic_value(&characteristic_info.id)
235 .await?)
236 }
237
238 async fn subscribe(&self, characteristic: &Characteristic) -> Result<()> {
239 let characteristic_info = self.characteristic_info(characteristic)?;
240 Ok(self.session.start_notify(&characteristic_info.id).await?)
241 }
242
243 async fn unsubscribe(&self, characteristic: &Characteristic) -> Result<()> {
244 let characteristic_info = self.characteristic_info(characteristic)?;
245 Ok(self.session.stop_notify(&characteristic_info.id).await?)
246 }
247
248 async fn notifications(&self) -> Result<Pin<Box<dyn Stream<Item = ValueNotification> + Send>>> {
249 let device_id = self.device.clone();
250 let events = self.session.device_event_stream(&device_id).await?;
251 let services = self.services.clone();
252 Ok(Box::pin(events.filter_map(move |event| {
253 ready(value_notification(event, &device_id, services.clone()))
254 })))
255 }
256
257 async fn write_descriptor(&self, descriptor: &Descriptor, data: &[u8]) -> Result<()> {
258 let descriptor_info = self.descriptor_info(descriptor)?;
259 Ok(self
260 .session
261 .write_descriptor_value(&descriptor_info.id, data)
262 .await?)
263 }
264
265 async fn read_descriptor(&self, descriptor: &Descriptor) -> Result<Vec<u8>> {
266 let descriptor_info = self.descriptor_info(descriptor)?;
267 Ok(self
268 .session
269 .read_descriptor_value(&descriptor_info.id)
270 .await?)
271 }
272}
273
274fn value_notification(
275 event: BluetoothEvent,
276 device_id: &DeviceId,
277 services: Arc<Mutex<HashMap<Uuid, ServiceInternal>>>,
278) -> Option<ValueNotification> {
279 match event {
280 BluetoothEvent::Characteristic {
281 id,
282 event: CharacteristicEvent::Value { value },
283 } if id.service().device() == *device_id => {
284 let services = services.lock().unwrap();
285 let uuid = find_characteristic_by_id(&services, id)?.uuid;
286 Some(ValueNotification { uuid, value })
287 }
288 _ => None,
289 }
290}
291
292fn find_characteristic_by_id(
293 services: &HashMap<Uuid, ServiceInternal>,
294 characteristic_id: CharacteristicId,
295) -> Option<&CharacteristicInfo> {
296 for service in services.values() {
297 for characteristic in service.characteristics.values() {
298 if characteristic.info.id == characteristic_id {
299 return Some(&characteristic.info);
300 }
301 }
302 }
303 None
304}
305
306impl From<WriteType> for bluez_async::WriteType {
307 fn from(write_type: WriteType) -> Self {
308 match write_type {
309 WriteType::WithoutResponse => bluez_async::WriteType::WithoutResponse,
310 WriteType::WithResponse => bluez_async::WriteType::WithResponse,
311 }
312 }
313}
314
315impl From<MacAddress> for BDAddr {
316 fn from(mac_address: MacAddress) -> Self {
317 <[u8; 6]>::into(mac_address.into())
318 }
319}
320
321impl From<DeviceId> for PeripheralId {
322 fn from(device_id: DeviceId) -> Self {
323 PeripheralId(device_id)
324 }
325}
326
327impl From<bluez_async::AddressType> for AddressType {
328 fn from(address_type: bluez_async::AddressType) -> Self {
329 match address_type {
330 bluez_async::AddressType::Public => AddressType::Public,
331 bluez_async::AddressType::Random => AddressType::Random,
332 }
333 }
334}
335
336fn make_descriptor(
337 info: &DescriptorInfo,
338 characteristic_uuid: Uuid,
339 service_uuid: Uuid,
340) -> Descriptor {
341 Descriptor {
342 uuid: info.uuid,
343 characteristic_uuid,
344 service_uuid,
345 }
346}
347
348fn make_characteristic(
349 characteristic: &CharacteristicInternal,
350 service_uuid: Uuid,
351) -> Characteristic {
352 let CharacteristicInternal { info, descriptors } = characteristic;
353 Characteristic {
354 uuid: info.uuid,
355 properties: info.flags.into(),
356 descriptors: descriptors
357 .iter()
358 .map(|(_, descriptor)| make_descriptor(descriptor, info.uuid, service_uuid))
359 .collect(),
360 service_uuid,
361 }
362}
363
364impl From<&ServiceInternal> for Service {
365 fn from(service: &ServiceInternal) -> Self {
366 Service {
367 uuid: service.info.uuid,
368 primary: service.info.primary,
369 characteristics: service
370 .characteristics
371 .values()
372 .map(|characteristic| make_characteristic(characteristic, service.info.uuid))
373 .collect(),
374 }
375 }
376}
377
378impl From<CharacteristicFlags> for CharPropFlags {
379 fn from(flags: CharacteristicFlags) -> Self {
380 let mut result = CharPropFlags::default();
381 if flags.contains(CharacteristicFlags::BROADCAST) {
382 result.insert(CharPropFlags::BROADCAST);
383 }
384 if flags.contains(CharacteristicFlags::READ) {
385 result.insert(CharPropFlags::READ);
386 }
387 if flags.contains(CharacteristicFlags::WRITE_WITHOUT_RESPONSE) {
388 result.insert(CharPropFlags::WRITE_WITHOUT_RESPONSE);
389 }
390 if flags.contains(CharacteristicFlags::WRITE) {
391 result.insert(CharPropFlags::WRITE);
392 }
393 if flags.contains(CharacteristicFlags::NOTIFY) {
394 result.insert(CharPropFlags::NOTIFY);
395 }
396 if flags.contains(CharacteristicFlags::INDICATE) {
397 result.insert(CharPropFlags::INDICATE);
398 }
399 if flags.contains(CharacteristicFlags::SIGNED_WRITE) {
400 result.insert(CharPropFlags::AUTHENTICATED_SIGNED_WRITES);
401 }
402 if flags.contains(CharacteristicFlags::EXTENDED_PROPERTIES) {
403 result.insert(CharPropFlags::EXTENDED_PROPERTIES);
404 }
405 result
406 }
407}