-
-
Notifications
You must be signed in to change notification settings - Fork 162
/
Copy pathadapter_manager.rs
90 lines (80 loc) · 2.75 KB
/
adapter_manager.rs
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
/// Implements common functionality for adapters across platforms.
// btleplug Source Code File
//
// Copyright 2020 Nonpolynomial Labs LLC. All rights reserved.
//
// Licensed under the BSD 3-Clause license. See LICENSE file in the project root
// for full license information.
//
// Some portions of this file are taken and/or modified from Rumble
// (https://github.com/mwylde/rumble), using a dual MIT/Apache License under the
// following copyright:
//
// Copyright (c) 2014 The Rust Project Developers
use crate::api::{CentralEvent, Peripheral};
use crate::platform::PeripheralId;
use dashmap::{mapref::one::RefMut, DashMap};
use futures::stream::{Stream, StreamExt};
use log::trace;
use std::pin::Pin;
use tokio::sync::broadcast;
use tokio_stream::wrappers::BroadcastStream;
#[derive(Debug)]
pub struct AdapterManager<PeripheralType>
where
PeripheralType: Peripheral,
{
peripherals: DashMap<PeripheralId, PeripheralType>,
events_channel: broadcast::Sender<CentralEvent>,
}
impl<PeripheralType: Peripheral + 'static> Default for AdapterManager<PeripheralType> {
fn default() -> Self {
let (broadcast_sender, _) = broadcast::channel(16);
AdapterManager {
peripherals: DashMap::new(),
events_channel: broadcast_sender,
}
}
}
impl<PeripheralType> AdapterManager<PeripheralType>
where
PeripheralType: Peripheral + 'static,
{
pub fn emit(&self, event: CentralEvent) {
if let CentralEvent::DeviceDisconnected(ref id) = event {
self.peripherals.remove(id);
}
if let Err(lost) = self.events_channel.send(event) {
trace!("Lost central event, while nothing subscribed: {:?}", lost);
}
}
pub fn event_stream(&self) -> Pin<Box<dyn Stream<Item = CentralEvent> + Send>> {
let receiver = self.events_channel.subscribe();
Box::pin(BroadcastStream::new(receiver).filter_map(|x| async move { x.ok() }))
}
pub fn add_peripheral(&self, peripheral: PeripheralType) {
assert!(
!self.peripherals.contains_key(&peripheral.id()),
"Adding a peripheral that's already in the map."
);
self.peripherals.insert(peripheral.id(), peripheral);
}
pub fn clear_peripherals(&self) {
self.peripherals.clear();
}
pub fn peripherals(&self) -> Vec<PeripheralType> {
self.peripherals
.iter()
.map(|val| val.value().clone())
.collect()
}
pub fn peripheral_mut(
&self,
id: &PeripheralId,
) -> Option<RefMut<PeripheralId, PeripheralType>> {
self.peripherals.get_mut(id)
}
pub fn peripheral(&self, id: &PeripheralId) -> Option<PeripheralType> {
self.peripherals.get(id).map(|val| val.value().clone())
}
}