forked from microsoft/Windows-universal-samples
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Scenario1_Discovery.xaml.cs
313 lines (274 loc) · 12.9 KB
/
Scenario1_Discovery.xaml.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
//*********************************************************
//
// Copyright (c) Microsoft. All rights reserved.
// This code is licensed under the MIT License (MIT).
// THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
// ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
// IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
// PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
//
//*********************************************************
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using Windows.Devices.Bluetooth;
using Windows.Devices.Enumeration;
using Windows.UI.Core;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Navigation;
namespace SDKTemplate
{
// This scenario uses a DeviceWatcher to enumerate nearby Bluetooth Low Energy devices,
// displays them in a ListView, and lets the user select a device and pair it.
// This device will be used by future scenarios.
// For more information about device discovery and pairing, including examples of
// customizing the pairing process, see the DeviceEnumerationAndPairing sample.
public sealed partial class Scenario1_Discovery : Page
{
private MainPage rootPage = MainPage.Current;
private ObservableCollection<BluetoothLEDeviceDisplay> KnownDevices = new ObservableCollection<BluetoothLEDeviceDisplay>();
private List<DeviceInformation> UnknownDevices = new List<DeviceInformation>();
private DeviceWatcher deviceWatcher;
#region UI Code
public Scenario1_Discovery()
{
InitializeComponent();
}
protected override void OnNavigatedFrom(NavigationEventArgs e)
{
StopBleDeviceWatcher();
// Save the selected device's ID for use in other scenarios.
var bleDeviceDisplay = ResultsListView.SelectedItem as BluetoothLEDeviceDisplay;
if (bleDeviceDisplay != null)
{
rootPage.SelectedBleDeviceId = bleDeviceDisplay.Id;
rootPage.SelectedBleDeviceName = bleDeviceDisplay.Name;
}
}
private void EnumerateButton_Click()
{
if (deviceWatcher == null)
{
StartBleDeviceWatcher();
EnumerateButton.Content = "Stop enumerating";
rootPage.NotifyUser($"Device watcher started.", NotifyType.StatusMessage);
}
else
{
StopBleDeviceWatcher();
EnumerateButton.Content = "Start enumerating";
rootPage.NotifyUser($"Device watcher stopped.", NotifyType.StatusMessage);
}
}
#endregion
#region Device discovery
/// <summary>
/// Starts a device watcher that looks for all nearby Bluetooth devices (paired or unpaired).
/// Attaches event handlers to populate the device collection.
/// </summary>
private void StartBleDeviceWatcher()
{
// Additional properties we would like about the device.
// Property strings are documented here https://msdn.microsoft.com/en-us/library/windows/desktop/ff521659(v=vs.85).aspx
string[] requestedProperties = { "System.Devices.Aep.DeviceAddress", "System.Devices.Aep.IsConnected", "System.Devices.Aep.Bluetooth.Le.IsConnectable" };
// BT_Code: Example showing paired and non-paired in a single query.
string aqsAllBluetoothLEDevices = "(System.Devices.Aep.ProtocolId:=\"{bb7bb05e-5972-42b5-94fc-76eaa7084d49}\")";
deviceWatcher =
DeviceInformation.CreateWatcher(
aqsAllBluetoothLEDevices,
requestedProperties,
DeviceInformationKind.AssociationEndpoint);
// Register event handlers before starting the watcher.
deviceWatcher.Added += DeviceWatcher_Added;
deviceWatcher.Updated += DeviceWatcher_Updated;
deviceWatcher.Removed += DeviceWatcher_Removed;
deviceWatcher.EnumerationCompleted += DeviceWatcher_EnumerationCompleted;
deviceWatcher.Stopped += DeviceWatcher_Stopped;
// Start over with an empty collection.
KnownDevices.Clear();
// Start the watcher.
deviceWatcher.Start();
}
/// <summary>
/// Stops watching for all nearby Bluetooth devices.
/// </summary>
private void StopBleDeviceWatcher()
{
if (deviceWatcher != null)
{
// Unregister the event handlers.
deviceWatcher.Added -= DeviceWatcher_Added;
deviceWatcher.Updated -= DeviceWatcher_Updated;
deviceWatcher.Removed -= DeviceWatcher_Removed;
deviceWatcher.EnumerationCompleted -= DeviceWatcher_EnumerationCompleted;
deviceWatcher.Stopped -= DeviceWatcher_Stopped;
// Stop the watcher.
deviceWatcher.Stop();
deviceWatcher = null;
}
}
private BluetoothLEDeviceDisplay FindBluetoothLEDeviceDisplay(string id)
{
foreach (BluetoothLEDeviceDisplay bleDeviceDisplay in KnownDevices)
{
if (bleDeviceDisplay.Id == id)
{
return bleDeviceDisplay;
}
}
return null;
}
private DeviceInformation FindUnknownDevices(string id)
{
foreach (DeviceInformation bleDeviceInfo in UnknownDevices)
{
if (bleDeviceInfo.Id == id)
{
return bleDeviceInfo;
}
}
return null;
}
private async void DeviceWatcher_Added(DeviceWatcher sender, DeviceInformation deviceInfo)
{
// We must update the collection on the UI thread because the collection is databound to a UI element.
await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
{
lock (this)
{
Debug.WriteLine(String.Format("Added {0}{1}", deviceInfo.Id, deviceInfo.Name));
// Protect against race condition if the task runs after the app stopped the deviceWatcher.
if (sender == deviceWatcher)
{
// Make sure device isn't already present in the list.
if (FindBluetoothLEDeviceDisplay(deviceInfo.Id) == null)
{
if (deviceInfo.Name != string.Empty)
{
// If device has a friendly name display it immediately.
KnownDevices.Add(new BluetoothLEDeviceDisplay(deviceInfo));
}
else
{
// Add it to a list in case the name gets updated later.
UnknownDevices.Add(deviceInfo);
}
}
}
}
});
}
private async void DeviceWatcher_Updated(DeviceWatcher sender, DeviceInformationUpdate deviceInfoUpdate)
{
// We must update the collection on the UI thread because the collection is databound to a UI element.
await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
{
lock (this)
{
Debug.WriteLine(String.Format("Updated {0}{1}", deviceInfoUpdate.Id, ""));
// Protect against race condition if the task runs after the app stopped the deviceWatcher.
if (sender == deviceWatcher)
{
BluetoothLEDeviceDisplay bleDeviceDisplay = FindBluetoothLEDeviceDisplay(deviceInfoUpdate.Id);
if (bleDeviceDisplay != null)
{
// Device is already being displayed - update UX.
bleDeviceDisplay.Update(deviceInfoUpdate);
return;
}
DeviceInformation deviceInfo = FindUnknownDevices(deviceInfoUpdate.Id);
if (deviceInfo != null)
{
deviceInfo.Update(deviceInfoUpdate);
// If device has been updated with a friendly name it's no longer unknown.
if (deviceInfo.Name != String.Empty)
{
KnownDevices.Add(new BluetoothLEDeviceDisplay(deviceInfo));
UnknownDevices.Remove(deviceInfo);
}
}
}
}
});
}
private async void DeviceWatcher_Removed(DeviceWatcher sender, DeviceInformationUpdate deviceInfoUpdate)
{
// We must update the collection on the UI thread because the collection is databound to a UI element.
await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
{
lock (this)
{
Debug.WriteLine(String.Format("Removed {0}{1}", deviceInfoUpdate.Id,""));
// Protect against race condition if the task runs after the app stopped the deviceWatcher.
if (sender == deviceWatcher)
{
// Find the corresponding DeviceInformation in the collection and remove it.
BluetoothLEDeviceDisplay bleDeviceDisplay = FindBluetoothLEDeviceDisplay(deviceInfoUpdate.Id);
if (bleDeviceDisplay != null)
{
KnownDevices.Remove(bleDeviceDisplay);
}
DeviceInformation deviceInfo = FindUnknownDevices(deviceInfoUpdate.Id);
if (deviceInfo != null)
{
UnknownDevices.Remove(deviceInfo);
}
}
}
});
}
private async void DeviceWatcher_EnumerationCompleted(DeviceWatcher sender, object e)
{
// We must update the collection on the UI thread because the collection is databound to a UI element.
await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
{
// Protect against race condition if the task runs after the app stopped the deviceWatcher.
if (sender == deviceWatcher)
{
rootPage.NotifyUser($"{KnownDevices.Count} devices found. Enumeration completed.",
NotifyType.StatusMessage);
}
});
}
private async void DeviceWatcher_Stopped(DeviceWatcher sender, object e)
{
// We must update the collection on the UI thread because the collection is databound to a UI element.
await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
{
// Protect against race condition if the task runs after the app stopped the deviceWatcher.
if (sender == deviceWatcher)
{
rootPage.NotifyUser($"No longer watching for devices.",
sender.Status == DeviceWatcherStatus.Aborted ? NotifyType.ErrorMessage : NotifyType.StatusMessage);
}
});
}
#endregion
#region Pairing
private bool isBusy = false;
private async void PairButton_Click()
{
// Do not allow a new Pair operation to start if an existing one is in progress.
if (isBusy)
{
return;
}
isBusy = true;
rootPage.NotifyUser("Pairing started. Please wait...", NotifyType.StatusMessage);
// For more information about device pairing, including examples of
// customizing the pairing process, see the DeviceEnumerationAndPairing sample.
// Capture the current selected item in case the user changes it while we are pairing.
var bleDeviceDisplay = ResultsListView.SelectedItem as BluetoothLEDeviceDisplay;
// BT_Code: Pair the currently selected device.
DevicePairingResult result = await bleDeviceDisplay.DeviceInformation.Pairing.PairAsync();
rootPage.NotifyUser($"Pairing result = {result.Status}",
result.Status == DevicePairingResultStatus.Paired || result.Status == DevicePairingResultStatus.AlreadyPaired
? NotifyType.StatusMessage
: NotifyType.ErrorMessage);
isBusy = false;
}
#endregion
}
}