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
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
use super::btleplug_internal::{
BtlePlugInternalEventLoop, DeviceReturnFuture, DeviceReturnStateShared,
};
use crate::{
core::{
errors::{ButtplugDeviceError, ButtplugError, ButtplugUnknownError},
messages::RawReading,
ButtplugResultFuture,
},
device::{
configuration_manager::{BluetoothLESpecifier, DeviceSpecifier, ProtocolDefinition},
ButtplugDeviceCommand, ButtplugDeviceEvent, ButtplugDeviceImplCreator, ButtplugDeviceReturn,
DeviceImpl, DeviceImplInternal, DeviceReadCmd, DeviceSubscribeCmd, DeviceUnsubscribeCmd,
DeviceWriteCmd,
},
util::async_manager,
};
use async_trait::async_trait;
use btleplug::api::{CentralEvent, Peripheral};
use futures::future::BoxFuture;
use std::{
fmt::{self, Debug},
sync::{
atomic::{AtomicBool, Ordering},
Arc,
},
};
use tokio::sync::{broadcast, mpsc};
use tracing_futures::Instrument;
pub struct BtlePlugDeviceImplCreator<T: Peripheral + 'static> {
device: Option<T>,
broadcaster: broadcast::Sender<CentralEvent>,
}
impl<T: Peripheral> BtlePlugDeviceImplCreator<T> {
pub fn new(device: T, broadcaster: broadcast::Sender<CentralEvent>) -> Self {
Self {
device: Some(device),
broadcaster,
}
}
}
impl<T: Peripheral> Debug for BtlePlugDeviceImplCreator<T> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("BtlePlugDeviceImplCreator").finish()
}
}
#[async_trait]
impl<T: Peripheral> ButtplugDeviceImplCreator for BtlePlugDeviceImplCreator<T> {
fn get_specifier(&self) -> DeviceSpecifier {
if self.device.is_none() {
panic!("Cannot call get_specifier after device is taken!");
}
let name = self
.device
.as_ref()
.unwrap()
.properties()
.local_name
.unwrap();
DeviceSpecifier::BluetoothLE(BluetoothLESpecifier::new_from_device(&name))
}
async fn try_create_device_impl(
&mut self,
protocol: ProtocolDefinition,
) -> Result<DeviceImpl, ButtplugError> {
if self.device.is_none() {
return Err(
ButtplugDeviceError::DeviceConnectionError(
"Cannot call try_create_device_impl twice!".to_owned(),
)
.into(),
);
}
let device = self.device.take().unwrap();
if let Some(ref proto) = protocol.btle {
let (device_sender, device_receiver) = mpsc::channel(256);
let name = device.properties().local_name.unwrap();
let address = device.properties().address.to_string();
let (device_event_sender, _) = broadcast::channel(256);
let mut event_loop = BtlePlugInternalEventLoop::new(
self.broadcaster.subscribe(),
device,
proto.clone(),
device_receiver,
device_event_sender.clone(),
);
async_manager::spawn(
async move { event_loop.run().await }.instrument(tracing::info_span!(
"btleplug Event Loop",
device = tracing::field::display(&name),
address = tracing::field::display(&address)
)),
)
.unwrap();
let fut = DeviceReturnFuture::default();
let waker = fut.get_state_clone();
if device_sender
.send((ButtplugDeviceCommand::Connect, waker))
.await
.is_err()
{
return Err(
ButtplugDeviceError::DeviceConnectionError(
"Event loop exited before we could connect.".to_owned(),
)
.into(),
);
};
match fut.await {
ButtplugDeviceReturn::Connected(info) => {
let device_internal_impl =
BtlePlugDeviceImpl::new(&address, device_sender, device_event_sender);
let device_impl = DeviceImpl::new(
&name,
&address,
&info.endpoints,
Box::new(device_internal_impl),
);
Ok(device_impl)
}
ButtplugDeviceReturn::Error(err) => Err(
ButtplugDeviceError::DeviceConnectionError(format!(
"Device connection failed: {:?}",
err
))
.into(),
),
other => Err(ButtplugUnknownError::UnexpectedType(format!("{:?}", other)).into()),
}
} else {
Err(
ButtplugDeviceError::DeviceConnectionError(
"Got a protocol with no Bluetooth Definition!".to_owned(),
)
.into(),
)
}
}
}
pub struct BtlePlugDeviceImpl {
address: String,
event_stream: broadcast::Sender<ButtplugDeviceEvent>,
thread_sender: mpsc::Sender<(ButtplugDeviceCommand, DeviceReturnStateShared)>,
connected: Arc<AtomicBool>,
}
unsafe impl Send for BtlePlugDeviceImpl {}
unsafe impl Sync for BtlePlugDeviceImpl {}
impl BtlePlugDeviceImpl {
pub fn new(
address: &str,
thread_sender: mpsc::Sender<(ButtplugDeviceCommand, DeviceReturnStateShared)>,
event_stream: broadcast::Sender<ButtplugDeviceEvent>,
) -> Self {
Self {
address: address.to_owned(),
thread_sender,
connected: Arc::new(AtomicBool::new(true)),
event_stream,
}
}
fn send_to_device_task(
&self,
cmd: ButtplugDeviceCommand,
) -> ButtplugResultFuture<ButtplugDeviceReturn> {
let sender = self.thread_sender.clone();
let connected = self.connected.clone();
let event_stream = self.event_stream.clone();
let address = self.address.clone();
Box::pin(async move {
let fut = DeviceReturnFuture::default();
let waker = fut.get_state_clone();
if sender.send((cmd, waker)).await.is_err() {
error!("Device event loop shut down, cannot send command.");
if connected.load(Ordering::SeqCst) {
connected.store(false, Ordering::SeqCst);
event_stream
.send(ButtplugDeviceEvent::Removed(address))
.unwrap();
}
return Err(
ButtplugDeviceError::DeviceNotConnected(
"Device event loop shut down, cannot send command.".to_owned(),
)
.into(),
);
}
Ok(fut.await)
})
}
fn send_to_device_expect_ok(
&self,
cmd: ButtplugDeviceCommand,
err_str: &str,
) -> ButtplugResultFuture {
let fut = self.send_to_device_task(cmd);
let err_fut_str = err_str.to_owned();
Box::pin(async move {
match fut.await? {
ButtplugDeviceReturn::Ok(_) => Ok(()),
ButtplugDeviceReturn::Error(e) => {
let err_out = format!("{}: {:?}", err_fut_str, e);
error!("{}", err_out);
Err(ButtplugDeviceError::DeviceCommunicationError(err_out).into())
}
other => {
Err(ButtplugUnknownError::UnexpectedType(format!("{}: {:?}", err_fut_str, other)).into())
}
}
})
}
}
impl DeviceImplInternal for BtlePlugDeviceImpl {
fn event_stream(&self) -> broadcast::Receiver<ButtplugDeviceEvent> {
self.event_stream.subscribe()
}
fn connected(&self) -> bool {
self.connected.load(Ordering::SeqCst)
}
fn disconnect(&self) -> ButtplugResultFuture {
self.send_to_device_expect_ok(
ButtplugDeviceCommand::Disconnect,
"Cannot disconnect device",
)
}
fn write_value(&self, msg: DeviceWriteCmd) -> ButtplugResultFuture {
self.send_to_device_expect_ok(
ButtplugDeviceCommand::Message(msg.into()),
"Cannot write to endpoint",
)
}
fn read_value(
&self,
msg: DeviceReadCmd,
) -> BoxFuture<'static, Result<RawReading, ButtplugError>> {
let task = self.send_to_device_task(ButtplugDeviceCommand::Message(msg.into()));
Box::pin(async move {
let val = task.await?;
if let ButtplugDeviceReturn::RawReading(reading) = val {
Ok(reading)
} else {
Err(
ButtplugUnknownError::UnexpectedType(format!(
"Read Error, unexpected return type: {:?}",
val
))
.into(),
)
}
})
}
fn subscribe(&self, msg: DeviceSubscribeCmd) -> ButtplugResultFuture {
self.send_to_device_expect_ok(
ButtplugDeviceCommand::Message(msg.into()),
"Cannot subscribe",
)
}
fn unsubscribe(&self, msg: DeviceUnsubscribeCmd) -> ButtplugResultFuture {
self.send_to_device_expect_ok(
ButtplugDeviceCommand::Message(msg.into()),
"Cannot unsubscribe",
)
}
}