/
DnaBluetoothLEAdvertisementWatcher.cs
379 lines (316 loc) · 12.4 KB
/
DnaBluetoothLEAdvertisementWatcher.cs
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
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Windows.Devices.Bluetooth;
using Windows.Devices.Bluetooth.Advertisement;
using Windows.Devices.Bluetooth.GenericAttributeProfile;
using Windows.Devices.Enumeration;
namespace Blueberry.Desktop.WindowsApp.Bluetooth
{
/// <summary>
/// Wraps and makes use of the <see cref="BluetoothLEAdvertisementWatcher"/>
/// for easier consumption
/// </summary>
public class DnaBluetoothLEAdvertisementWatcher
{
#region Private Members
/// <summary>
/// The underlying bluetooth watcher class
/// </summary>
private readonly BluetoothLEAdvertisementWatcher mWatcher;
/// <summary>
/// A list of discovered devices
/// </summary>
private readonly Dictionary<string, DnaBluetoothLEDevice> mDiscoveredDevices = new Dictionary<string, DnaBluetoothLEDevice>();
/// <summary>
/// The details about GATT services
/// </summary>
private readonly GattServiceIds mGattServiceIds;
/// <summary>
/// A thread lock object for this class
/// </summary>
private readonly object mThreadLock = new object();
#endregion
#region Public Properties
/// <summary>
/// Indicates if this watcher is listening for advertisements
/// </summary>
public bool Listening => mWatcher.Status == BluetoothLEAdvertisementWatcherStatus.Started;
/// <summary>
/// A list of discovered devices
/// </summary>
public IReadOnlyCollection<DnaBluetoothLEDevice> DiscoveredDevices
{
get
{
// Clean up any timeouts
CleanupTimeouts();
// Practice thread-safety kids!
lock (mThreadLock)
{
// Convert to read-only list
return mDiscoveredDevices.Values.ToList().AsReadOnly();
}
}
}
/// <summary>
/// The timeout in seconds that a device is removed from the <see cref="DiscoveredDevices"/>
/// list if it is not re-advertised within this time
/// </summary>
public int HeartbeatTimeout { get; set; } = 30;
#endregion
#region Public Events
/// <summary>
/// Fired when the bluetooth watcher stops listening
/// </summary>
public event Action StoppedListening = () => { };
/// <summary>
/// Fired when the bluetooth watcher starts listening
/// </summary>
public event Action StartedListening = () => { };
/// <summary>
/// Fired when a device is discovered
/// </summary>
public event Action<DnaBluetoothLEDevice> DeviceDiscovered = (device) => { };
/// <summary>
/// Fired when a new device is discovered
/// </summary>
public event Action<DnaBluetoothLEDevice> NewDeviceDiscovered = (device) => { };
/// <summary>
/// Fired when a device name changes
/// </summary>
public event Action<DnaBluetoothLEDevice> DeviceNameChanged = (device) => { };
/// <summary>
/// Fired when a device is removed for timing out
/// </summary>
public event Action<DnaBluetoothLEDevice> DeviceTimeout = (device) => { };
#endregion
#region Constructor
/// <summary>
/// The default constructor
/// </summary>
public DnaBluetoothLEAdvertisementWatcher(GattServiceIds gattIds)
{
// Null guard
mGattServiceIds = gattIds ?? throw new ArgumentNullException(nameof(gattIds));
// Create bluetooth listener
mWatcher = new BluetoothLEAdvertisementWatcher
{
ScanningMode = BluetoothLEScanningMode.Active
};
// Listen out for new advertisements
mWatcher.Received += WatcherAdvertisementReceivedAsync;
// Listen out for when the watcher stops listening
mWatcher.Stopped += (watcher, e) =>
{
// Inform listeners
StoppedListening();
};
}
#endregion
#region Private Methods
/// <summary>
/// Listens out for watcher advertisements
/// </summary>
/// <param name="sender">The watcher</param>
/// <param name="args">The arguments</param>
private async void WatcherAdvertisementReceivedAsync(BluetoothLEAdvertisementWatcher sender, BluetoothLEAdvertisementReceivedEventArgs args)
{
// Cleanup Timeouts
CleanupTimeouts();
// Get BLE device info
var device = await GetBluetoothLEDeviceAsync(
args.BluetoothAddress,
args.Timestamp,
args.RawSignalStrengthInDBm);
// Null guard
if (device == null)
return;
// Is new discovery?
var newDiscovery = false;
var existingName = default(string);
var nameChanged = false;
// Lock your doors
lock (mThreadLock)
{
// Check if this is a new discovery
newDiscovery = !mDiscoveredDevices.ContainsKey(device.DeviceId);
// If this is not new...
if (!newDiscovery)
// Store the old name
existingName = mDiscoveredDevices[device.DeviceId].Name;
// Name changed?
nameChanged =
// If it already exists
!newDiscovery &&
// And is not a blank name
!string.IsNullOrEmpty(device.Name) &&
// And the name is different
existingName != device.Name;
// If we are no longer listening...
if (!Listening)
// Don't bother adding to the list and do nothing
return;
// Add/update the device in the dictionary
mDiscoveredDevices[device.DeviceId] = device;
}
// Inform listeners
DeviceDiscovered(device);
// If name changed...
if (nameChanged)
// Inform listeners
DeviceNameChanged(device);
// If new discovery...
if (newDiscovery)
// Inform listeners
NewDeviceDiscovered(device);
}
/// <summary>
/// Connects to the BLE device and extracts more information from the
/// <see cref="https://docs.microsoft.com/en-us/uwp/api/windows.devices.bluetooth.bluetoothledevice"/>
/// </summary>
/// <param name="address">The BT address of the device to connect to</param>
/// <param name="broadcastTime">The time the broadcast message was received</param>
/// <param name="rssi">The signal strength in dB</param>
/// <returns></returns>
private async Task<DnaBluetoothLEDevice> GetBluetoothLEDeviceAsync(ulong address, DateTimeOffset broadcastTime, short rssi)
{
// Get bluetooth device info
using var device = await BluetoothLEDevice.FromBluetoothAddressAsync(address).AsTask();
// Null guard
if (device == null)
return null;
// NOTE: This can throw a System.Exception for failures
// Get GATT services that are available
var gatt = await device.GetGattServicesAsync().AsTask();
// If we have any services...
if (gatt.Status == GattCommunicationStatus.Success)
{
// Loop each GATT service
foreach (var service in gatt.Services)
{
// This ID contains the GATT Profile Assigned number we want!
// TODO: Get more info and connect
var gattProfileId = service.Uuid;
}
}
// Return the new device information
return new DnaBluetoothLEDevice
(
// Device Id
deviceId: device.DeviceId,
// Bluetooth Address
address: device.BluetoothAddress,
// Device Name
name: device.Name,
// Broadcast Time
broadcastTime: broadcastTime,
// Signal Strength
rssi: rssi,
// Is Connected?
connected: device.ConnectionStatus == BluetoothConnectionStatus.Connected,
// Can Pair?
canPair: device.DeviceInformation.Pairing.CanPair,
// Is Paired?
paired: device.DeviceInformation.Pairing.IsPaired
);
}
/// <summary>
/// Prune any timed out devices that we have not heard off
/// </summary>
private void CleanupTimeouts()
{
lock (mThreadLock)
{
// The date in time that if less than means a device has timed out
var threshold = DateTime.UtcNow - TimeSpan.FromSeconds(HeartbeatTimeout);
// Any devices that have not sent a new broadcast within the heartbeat time
mDiscoveredDevices.Where(f => f.Value.BroadcastTime < threshold).ToList().ForEach(device =>
{
// Remove device
mDiscoveredDevices.Remove(device.Key);
// Inform listeners
DeviceTimeout(device.Value);
});
}
}
#endregion
#region Public Methods
/// <summary>
/// Starts listening for advertisements
/// </summary>
public void StartListening()
{
lock (mThreadLock)
{
// If already listening...
if (Listening)
// Do nothing more
return;
// Start the underlying watcher
mWatcher.Start();
}
// Inform listeners
StartedListening();
}
/// <summary>
/// Stops listening for advertisements
/// </summary>
public void StopListening()
{
lock (mThreadLock)
{
// If we are no currently listening...
if (!Listening)
// Do nothing more
return;
// Stop listening
mWatcher.Stop();
// Clear any devices
mDiscoveredDevices.Clear();
}
}
/// <summary>
/// Attempts to pair to a BLE device, by ID
/// </summary>
/// <param name="deviceId">The BLE device ID</param>
/// <returns></returns>
public async Task PairToDeviceAsync(string deviceId)
{
// Get bluetooth device info
using var device = await BluetoothLEDevice.FromIdAsync(deviceId).AsTask();
// Null guard
if (device == null)
// TODO: Localize
throw new ArgumentNullException("Failed to get information about the Bluetooth device");
// If we are already paired...
if (device.DeviceInformation.Pairing.IsPaired)
// Do nothing
return;
// Listen out for pairing request
device.DeviceInformation.Pairing.Custom.PairingRequested += (sender, args) =>
{
// Log it
// TODO: Remove
Console.WriteLine("Accepting pairing request...");
// Accept all attempts
args.Accept(); // <-- Could enter a pin in here to accept
};
// Try and pair to the device
var result = await device.DeviceInformation.Pairing.Custom.PairAsync(
// For Contour we should try Provide Pin
// TODO: Try different types to see if any work
DevicePairingKinds.ProvidePin
).AsTask();
// Log the result
if (result.Status == DevicePairingResultStatus.Paired)
// TODO: Remove
Console.WriteLine("Pairing successful");
else
// TODO: Remove
Console.WriteLine($"Pairing failed: {result.Status}");
}
#endregion
}
}