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
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
// 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.
use super::{
adapter::uuid_to_bdaddr,
internal::{
CBPeripheralEvent, CoreBluetoothMessage, CoreBluetoothReply, CoreBluetoothReplyFuture,
},
};
use crate::{
api::{
AdapterManager, AddressType, BDAddr, CentralEvent, Characteristic, CommandCallback,
NotificationHandler, Peripheral as ApiPeripheral, PeripheralProperties, RequestCallback,
ValueNotification, UUID,
},
common::util,
Error, Result,
};
use async_std::{
prelude::StreamExt,
sync::{Receiver, Sender},
task,
};
use std::{
collections::BTreeSet,
fmt::{self, Debug, Display, Formatter},
iter::FromIterator,
sync::{Arc, Mutex},
};
use uuid::Uuid;
#[derive(Clone)]
pub struct Peripheral {
notification_handlers: Arc<Mutex<Vec<NotificationHandler>>>,
manager: AdapterManager<Self>,
uuid: Uuid,
characteristics: Arc<Mutex<BTreeSet<Characteristic>>>,
pub(crate) properties: PeripheralProperties,
event_receiver: Receiver<CBPeripheralEvent>,
message_sender: Sender<CoreBluetoothMessage>,
// We're not actually holding a peripheral object here, that's held out in
// the objc thread. We'll just communicate with it through our
// receiver/sender pair.
}
impl Peripheral {
pub fn new(
uuid: Uuid,
local_name: String,
manager: AdapterManager<Self>,
event_receiver: Receiver<CBPeripheralEvent>,
message_sender: Sender<CoreBluetoothMessage>,
) -> Self {
// Since we're building the object, we have an active advertisement.
// Build properties now.
let properties = PeripheralProperties {
// Rumble required ONLY a BDAddr, not something you can get from
// MacOS, so we make it up for now. This sucks.
address: uuid_to_bdaddr(&uuid.to_string()),
address_type: AddressType::Random,
local_name: Some(local_name),
tx_power_level: None,
manufacturer_data: None,
discovery_count: 1,
has_scan_response: true,
};
let notification_handlers = Arc::new(Mutex::new(Vec::<NotificationHandler>::new()));
let mut er_clone = event_receiver.clone();
let nh_clone = notification_handlers.clone();
task::spawn(async move {
loop {
let event = er_clone.next().await;
if event.is_none() {
error!("Event receiver died, breaking out of corebluetooth device loop.");
break;
}
if let Some(CBPeripheralEvent::Notification(uuid, data)) = event {
let mut id = *uuid.as_bytes();
id.reverse();
util::invoke_handlers(
&nh_clone,
&ValueNotification {
uuid: UUID::B128(id),
handle: None,
value: data,
},
);
} else {
error!("Unhandled CBPeripheralEvent");
}
}
});
Self {
properties,
manager,
characteristics: Arc::new(Mutex::new(BTreeSet::new())),
notification_handlers,
uuid,
event_receiver,
message_sender,
}
}
fn emit(&self, event: CentralEvent) {
debug!("emitted {:?}", event);
self.manager.emit(event)
}
}
impl Display for Peripheral {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
// let connected = if self.is_connected() { " connected" } else { "" };
// let properties = self.properties.lock().unwrap();
// write!(f, "{} {}{}", self.address, properties.local_name.clone()
// .unwrap_or_else(|| "(unknown)".to_string()), connected)
write!(f, "Peripheral")
}
}
impl Debug for Peripheral {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
// let connected = if self.is_connected() { " connected" } else { "" };
// let properties = self.properties.lock().unwrap();
// let characteristics = self.characteristics.lock().unwrap();
// write!(f, "{} properties: {:?}, characteristics: {:?} {}", self.address, *properties,
// *characteristics, connected)
write!(f, "Peripheral")
}
}
fn get_apple_uuid(uuid: UUID) -> Uuid {
let mut u;
if let UUID::B128(big_u) = uuid {
u = big_u;
} else {
panic!("Wrong UUID type!");
}
u.reverse();
Uuid::from_bytes(u)
}
impl ApiPeripheral for Peripheral {
/// Returns the address of the peripheral.
fn address(&self) -> BDAddr {
self.properties.address
}
/// Returns the set of properties associated with the peripheral. These may be updated over time
/// as additional advertising reports are received.
fn properties(&self) -> PeripheralProperties {
self.properties.clone()
}
/// The set of characteristics we've discovered for this device. This will be empty until
/// `discover_characteristics` or `discover_characteristics_in_range` is called.
fn characteristics(&self) -> BTreeSet<Characteristic> {
self.characteristics.lock().unwrap().clone()
}
/// Returns true iff we are currently connected to the device.
fn is_connected(&self) -> bool {
false
}
/// Creates a connection to the device. This is a synchronous operation; if this method returns
/// Ok there has been successful connection. Note that peripherals allow only one connection at
/// a time. Operations that attempt to communicate with a device will fail until it is connected.
fn connect(&self) -> Result<()> {
info!("Trying device connect!");
task::block_on(async {
let fut = CoreBluetoothReplyFuture::default();
self.message_sender
.send(CoreBluetoothMessage::ConnectDevice(
self.uuid,
fut.get_state_clone(),
))
.await;
match fut.await {
CoreBluetoothReply::Connected(chars) => {
*(self.characteristics.lock().unwrap()) = chars;
self.emit(CentralEvent::DeviceConnected(self.properties.address));
}
_ => panic!("Shouldn't get anything but connected!"),
}
});
info!("Device connected!");
Ok(())
}
/// Terminates a connection to the device. This is a synchronous operation.
fn disconnect(&self) -> Result<()> {
Ok(())
}
/// Discovers all characteristics for the device. This is a synchronous operation.
fn discover_characteristics(&self) -> Result<Vec<Characteristic>> {
let chrs = self.characteristics.lock().unwrap().clone();
let v = Vec::from_iter(chrs.into_iter());
Ok(v)
}
/// Discovers characteristics within the specified range of handles. This is a synchronous
/// operation.
fn discover_characteristics_in_range(
&self,
_start: u16,
_end: u16,
) -> Result<Vec<Characteristic>> {
panic!("NOT IMPLEMENTED");
}
/// Sends a command (`write-without-response`) to the characteristic. Takes an optional callback
/// that will be notified in case of error or when the command has been successfully acked by the
/// device.
fn command_async(
&self,
_characteristic: &Characteristic,
_data: &[u8],
_handler: Option<CommandCallback>,
) {
info!("Trying to command!");
}
/// Sends a command (write without response) to the characteristic. Synchronously returns a
/// `Result` with an error set if the command was not accepted by the device.
fn command(&self, characteristic: &Characteristic, data: &[u8]) -> Result<()> {
info!("Trying to command!");
task::block_on(async {
let fut = CoreBluetoothReplyFuture::default();
self.message_sender
.send(CoreBluetoothMessage::WriteValue(
self.uuid,
get_apple_uuid(characteristic.uuid),
Vec::from(data),
fut.get_state_clone(),
))
.await;
match fut.await {
CoreBluetoothReply::Ok => {}
_ => panic!("Didn't subscribe!"),
}
});
Ok(())
}
/// Sends a request (write) to the device. Takes an optional callback with either an error if
/// the request was not accepted or the response from the device.
fn request_async(
&self,
_characteristic: &Characteristic,
_data: &[u8],
_handler: Option<RequestCallback>,
) {
}
/// Sends a request (write) to the device. Synchronously returns either an error if the request
/// was not accepted or the response from the device.
fn request(&self, _characteristic: &Characteristic, _data: &[u8]) -> Result<Vec<u8>> {
Ok(Vec::new())
}
/// Sends a read-by-type request to device for the range of handles covered by the
/// characteristic and for the specified declaration UUID. See
/// [here](https://www.bluetooth.com/specifications/gatt/declarations) for valid UUIDs.
/// Takes an optional callback that will be called with an error or the device response.
fn read_by_type_async(
&self,
_characteristic: &Characteristic,
_uuid: UUID,
_handler: Option<RequestCallback>,
) {
}
/// Sends a read-by-type request to device for the range of handles covered by the
/// characteristic and for the specified declaration UUID. See
/// [here](https://www.bluetooth.com/specifications/gatt/declarations) for valid UUIDs.
/// Synchronously returns either an error or the device response.
fn read_by_type(&self, _characteristic: &Characteristic, _uuid: UUID) -> Result<Vec<u8>> {
Err(Error::NotSupported("read_by_type".into()))
}
/// Enables either notify or indicate (depending on support) for the specified characteristic.
/// This is a synchronous call.
fn subscribe(&self, characteristic: &Characteristic) -> Result<()> {
info!("Trying to subscribe!");
task::block_on(async {
let fut = CoreBluetoothReplyFuture::default();
self.message_sender
.send(CoreBluetoothMessage::Subscribe(
self.uuid,
get_apple_uuid(characteristic.uuid),
fut.get_state_clone(),
))
.await;
match fut.await {
CoreBluetoothReply::Ok => info!("subscribed!"),
_ => panic!("Didn't subscribe!"),
}
});
Ok(())
}
/// Disables either notify or indicate (depending on support) for the specified characteristic.
/// This is a synchronous call.
fn unsubscribe(&self, characteristic: &Characteristic) -> Result<()> {
info!("Trying to unsubscribe!");
task::block_on(async {
let fut = CoreBluetoothReplyFuture::default();
self.message_sender
.send(CoreBluetoothMessage::Unsubscribe(
self.uuid,
get_apple_uuid(characteristic.uuid),
fut.get_state_clone(),
))
.await;
match fut.await {
CoreBluetoothReply::Ok => {}
_ => panic!("Didn't unsubscribe!"),
}
});
Ok(())
}
/// Registers a handler that will be called when value notification messages are received from
/// the device. This method should only be used after a connection has been established. Note
/// that the handler will be called in a common thread, so it should not block.
fn on_notification(&self, handler: NotificationHandler) {
let mut list = self.notification_handlers.lock().unwrap();
list.push(handler);
}
fn read_async(&self, _characteristic: &Characteristic, _handler: Option<RequestCallback>) {}
fn read(&self, _characteristic: &Characteristic) -> Result<Vec<u8>> {
Ok(vec![])
}
}