This repository has been archived by the owner on Jan 10, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBlueToothCore.cs
418 lines (369 loc) · 13.8 KB
/
BlueToothCore.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
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
using System;
using System.Collections.Generic;
using System.Diagnostics;
using Windows.Devices.Bluetooth;
using Windows.Devices.Bluetooth.Advertisement;
using Windows.Devices.Bluetooth.GenericAttributeProfile;
using Windows.Foundation;
using Windows.Security.Cryptography;
namespace BlueToothModelCar;
internal class BlueToothCore
{
/// <summary>
/// 获取特征委托
/// </summary>
public delegate void CharacteristicAddedEvent(GattCharacteristic gattCharacteristic);
/// <summary>
/// 获取服务委托
/// </summary>
public delegate void CharacteristicFinishEvent(int size);
/// <summary>
/// 定义搜索蓝牙设备委托
/// </summary>
public delegate void DeviceWatcherChangedEvent(BluetoothLEDevice bluetoothLeDevice);
/// <summary>
/// 接受数据委托
/// </summary>
/// <param name="sender"></param>
/// <param name="data"></param>
public delegate void RecDataEvent(GattCharacteristic sender, byte[] data);
/// <summary>
/// 特性通知类型通知启用
/// </summary>
private const GattClientCharacteristicConfigurationDescriptorValue CharacteristicNotificationType = GattClientCharacteristicConfigurationDescriptorValue.Notify;
private bool _asyncLock;
private BluetoothLEAdvertisementWatcher? _watcher;
public HashSet<GattCharacteristic> Characteristics = [];
public BlueToothCore() => CharacteristicAdded += OnCharacteristicAdded;
/// <summary>
/// 当前连接的服务
/// </summary>
public GattDeviceService? CurrentService { get; private set; }
/// <summary>
/// 当前连接的蓝牙设备
/// </summary>
public BluetoothLEDevice? CurrentDevice { get; private set; }
/// <summary>
/// 写特征对象
/// </summary>
public GattCharacteristic? CurrentWriteCharacteristic { get; private set; }
/// <summary>
/// 通知特征对象
/// </summary>
public GattCharacteristic? CurrentNotifyCharacteristic { get; private set; }
/// <summary>
/// 存储检测到的设备
/// </summary>
public Dictionary<string, BluetoothLEDevice> DeviceList { get; } = [];
/// <summary>
/// 当前连接的蓝牙Mac
/// </summary>
private string CurrentDeviceMac { get; set; } = "";
/// <summary>
/// 搜索蓝牙事件
/// </summary>
public event Action<BluetoothLEDevice>? NewDevice;
/// <summary>
/// 搜索蓝牙事件
/// </summary>
public event DeviceWatcherChangedEvent? DeviceWatcherChanged;
/// <summary>
/// 获取服务事件
/// </summary>
public event CharacteristicFinishEvent? CharacteristicFinish;
/// <summary>
/// 获取特征事件
/// </summary>
public event CharacteristicAddedEvent? CharacteristicAdded;
/// <summary>
/// 接受数据事件
/// </summary>
public event RecDataEvent? RecData;
private void OnCharacteristicAdded(GattCharacteristic gatt)
{
Debug.WriteLine($"handle:[0x{gatt.AttributeHandle:X4}] char properties:[{gatt.CharacteristicProperties}] UUID:[{gatt.Uuid}]");
_ = Characteristics.Add(gatt);
if (gatt.CharacteristicProperties.HasFlag(GattCharacteristicProperties.Write) ||gatt.CharacteristicProperties.HasFlag(GattCharacteristicProperties.Notify))
SetOperation(gatt);
}
/// <summary>
/// 搜索蓝牙设备
/// </summary>
public void StartBleDeviceWatcher()
{
_watcher = new()
{
ScanningMode = BluetoothLEScanningMode.Active,
SignalStrengthFilter = {
// only activate the watcher when we're recieving values >= -80
InRangeThresholdInDBm = -80,
// stop watching if the value drops below -90 (user walked away)
OutOfRangeThresholdInDBm = -90
}
};
// register callback for when we see an advertisements
_watcher.Received += OnAdvertisementReceived;
// wait 5 seconds to make sure the device is really out of range
_watcher.SignalStrengthFilter.OutOfRangeTimeout = TimeSpan.FromMilliseconds(5000);
_watcher.SignalStrengthFilter.SamplingInterval = TimeSpan.FromMilliseconds(2000);
// starting watching for advertisements
_watcher.Start();
Debug.WriteLine("自动发现设备中..");
}
/// <summary>
/// 停止搜索蓝牙
/// </summary>
public void StopBleDeviceWatcher() => _watcher?.Stop();
/// <summary>
/// 主动断开连接
/// </summary>
/// <returns></returns>
public void Dispose()
{
CurrentDeviceMac = "";
CurrentService?.Dispose();
CurrentDevice?.Dispose();
CurrentService = null;
CurrentDevice = null;
CurrentWriteCharacteristic = null;
CurrentNotifyCharacteristic = null;
Debug.WriteLine("主动断开连接");
}
/// <summary>
/// 匹配
/// </summary>
/// <param name="device"></param>
public void StartMatching(BluetoothLEDevice device) => CurrentDevice = device;
/// <summary>
/// 发送数据接口
/// </summary>
/// <returns></returns>
public void Write(params byte[] data)
{
if (CurrentWriteCharacteristic != null)
{
CurrentWriteCharacteristic.WriteValueAsync(CryptographicBuffer.CreateFromByteArray(data), GattWriteOption.WriteWithResponse).Completed = (asyncInfo, asyncStatus) =>
{
if (asyncStatus == AsyncStatus.Completed)
{
var a = asyncInfo.GetResults();
Debug.WriteLine("发送数据:" + BitConverter.ToString(data) + " State : " + a);
}
};
}
}
/// <summary>
/// 获取蓝牙服务
/// </summary>
public void FindService()
{
if (CurrentDevice is null)
return;
CurrentDevice.GetGattServicesAsync().Completed = (asyncInfo, asyncStatus) =>
{
if (asyncStatus == AsyncStatus.Completed)
{
var services = asyncInfo.GetResults().Services;
Debug.WriteLine("GattServices size=" + services.Count);
foreach (var ser in services)
{
FindCharacteristic(ser);
}
CharacteristicFinish?.Invoke(services.Count);
}
};
}
/// <summary>
/// 按MAC地址直接组装设备ID查找设备
/// </summary>
public void SelectDeviceFromIdAsync(string mac)
{
CurrentDeviceMac = mac;
CurrentDevice = null;
BluetoothAdapter.GetDefaultAsync().Completed = (asyncInfo, asyncStatus) =>
{
if (asyncStatus == AsyncStatus.Completed)
{
var mBluetoothAdapter = asyncInfo.GetResults();
var bytes1 = BitConverter.GetBytes(mBluetoothAdapter.BluetoothAddress);//ulong转换为byte数组
Array.Reverse(bytes1);
var macAddress = BitConverter.ToString(bytes1, 2, 6).Replace('-', ':').ToLower();
var id = "BluetoothLE#BluetoothLE" + macAddress + "-" + mac;
Matching(id);
}
};
}
/// <summary>
/// 获取操作
/// </summary>
/// <returns></returns>
public void SetOperation(GattCharacteristic gattCharacteristic)
{
if (CurrentDevice is null)
return;
var bytes1 = BitConverter.GetBytes(CurrentDevice.BluetoothAddress);
Array.Reverse(bytes1);
CurrentDeviceMac = BitConverter.ToString(bytes1, 2, 6).Replace('-', ':').ToLower();
var msg = "正在连接设备<" + CurrentDeviceMac + ">..";
Debug.WriteLine(msg);
if (gattCharacteristic.CharacteristicProperties.HasFlag(GattCharacteristicProperties.Write))
CurrentWriteCharacteristic = gattCharacteristic;
if (gattCharacteristic.CharacteristicProperties.HasFlag(GattCharacteristicProperties.Notify))
{
CurrentNotifyCharacteristic = gattCharacteristic;
CurrentNotifyCharacteristic.ProtectionLevel = GattProtectionLevel.Plain;
CurrentNotifyCharacteristic.ValueChanged += Characteristic_ValueChanged;
EnableNotifications(CurrentNotifyCharacteristic);
}
if ((uint)gattCharacteristic.CharacteristicProperties is 26)
{
}
if (gattCharacteristic.CharacteristicProperties is (GattCharacteristicProperties.Write | GattCharacteristicProperties.Notify))
{
CurrentWriteCharacteristic = gattCharacteristic;
CurrentNotifyCharacteristic = gattCharacteristic;
CurrentNotifyCharacteristic.ProtectionLevel = GattProtectionLevel.Plain;
CurrentNotifyCharacteristic.ValueChanged += Characteristic_ValueChanged;
EnableNotifications(CurrentNotifyCharacteristic);
}
CurrentDevice.ConnectionStatusChanged += CurrentDevice_ConnectionStatusChanged;
}
private void OnAdvertisementReceived(BluetoothLEAdvertisementWatcher watcher, BluetoothLEAdvertisementReceivedEventArgs eventArgs) =>
BluetoothLEDevice.FromBluetoothAddressAsync(eventArgs.BluetoothAddress).Completed = (asyncInfo, asyncStatus) =>
{
if (asyncStatus == AsyncStatus.Completed)
{
if (asyncInfo.GetResults() == null)
{
//Debug.WriteLine("没有得到结果集");
}
else
{
var currentDevice = asyncInfo.GetResults();
if (DeviceList.TryAdd(currentDevice.DeviceId, currentDevice))
{
NewDevice?.Invoke(currentDevice);
DeviceWatcherChanged?.Invoke(currentDevice);
}
else
currentDevice.Dispose();
}
}
};
/// <summary>
/// 获取特性
/// </summary>
private void FindCharacteristic(GattDeviceService gattDeviceService)
{
CurrentService = gattDeviceService;
CurrentService.GetCharacteristicsAsync().Completed = (asyncInfo, asyncStatus) =>
{
if (asyncStatus == AsyncStatus.Completed)
{
var services = asyncInfo.GetResults().Characteristics;
foreach (var c in services)
{
CharacteristicAdded?.Invoke(c);
}
}
};
}
/// <summary>
/// 搜索到的蓝牙设备
/// </summary>
/// <returns></returns>
private void Matching(string id)
{
try
{
BluetoothLEDevice.FromIdAsync(id).Completed = (asyncInfo, asyncStatus) =>
{
switch (asyncStatus)
{
case AsyncStatus.Completed:
{
var bleDevice = asyncInfo.GetResults();
if (DeviceList.TryAdd(bleDevice.DeviceId, bleDevice))
NewDevice?.Invoke(bleDevice);
NewDevice?.Invoke(bleDevice);
Debug.WriteLine(bleDevice);
break;
}
case AsyncStatus.Started:
case AsyncStatus.Canceled:
case AsyncStatus.Error:
Debug.WriteLine(asyncStatus.ToString());
break;
}
};
}
catch (Exception e)
{
var msg = "没有发现设备" + e;
Debug.WriteLine(msg);
StartBleDeviceWatcher();
}
}
private void CurrentDevice_ConnectionStatusChanged(BluetoothLEDevice sender, object args)
{
if (sender.ConnectionStatus == BluetoothConnectionStatus.Disconnected && CurrentDeviceMac != "")
{
if (!_asyncLock)
{
_asyncLock = true;
Debug.WriteLine("设备已断开");
CurrentDevice?.Dispose();
CurrentDevice = null;
CurrentService = null;
CurrentWriteCharacteristic = null;
CurrentNotifyCharacteristic = null;
SelectDeviceFromIdAsync(CurrentDeviceMac);
}
}
else
{
if (!_asyncLock)
{
_asyncLock = true;
Debug.WriteLine("设备已连接");
}
}
}
/// <summary>
/// 设置特征对象为接收通知对象
/// </summary>
/// <param name="characteristic"></param>
/// <returns></returns>
private void EnableNotifications(GattCharacteristic characteristic)
{
if (CurrentDevice is null)
return;
Debug.WriteLine("收通知对象=" + CurrentDevice.Name + ":" + CurrentDevice.ConnectionStatus);
characteristic.WriteClientCharacteristicConfigurationDescriptorAsync(CharacteristicNotificationType).Completed = (asyncInfo, asyncStatus) =>
{
if (asyncStatus == AsyncStatus.Completed)
{
var status = asyncInfo.GetResults();
if (status == GattCommunicationStatus.Unreachable)
{
Debug.WriteLine("设备不可用");
if (CurrentNotifyCharacteristic != null && !_asyncLock)
{
EnableNotifications(CurrentNotifyCharacteristic);
}
return;
}
_asyncLock = false;
Debug.WriteLine("设备连接状态" + status);
}
};
}
/// <summary>
/// 接受到蓝牙数据
/// </summary>
private void Characteristic_ValueChanged(GattCharacteristic sender, GattValueChangedEventArgs args)
{
CryptographicBuffer.CopyToByteArray(args.CharacteristicValue, out var data);
RecData?.Invoke(sender, data);
}
}