-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBleDeviceScanner.cs
More file actions
190 lines (160 loc) · 6.16 KB
/
BleDeviceScanner.cs
File metadata and controls
190 lines (160 loc) · 6.16 KB
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
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.Enumeration;
namespace WatchPatBLE;
/// <summary>
/// Scans for ITAMAR WatchPAT BLE devices
/// </summary>
public class BleDeviceScanner : IDisposable
{
private readonly BluetoothLEAdvertisementWatcher _watcher;
private readonly Dictionary<ulong, DeviceInfo> _discoveredDevices;
private readonly object _lock = new object();
private TaskCompletionSource<List<DeviceInfo>> _scanCompletionSource;
public event EventHandler<DeviceInfo> DeviceDiscovered;
public class DeviceInfo
{
public string Name { get; set; }
public string SerialNumber { get; set; }
public ulong BluetoothAddress { get; set; }
public short SignalStrength { get; set; }
public bool IsNew { get; set; }
public DateTime LastSeen { get; set; }
}
public BleDeviceScanner()
{
_discoveredDevices = new Dictionary<ulong, DeviceInfo>();
_watcher = new BluetoothLEAdvertisementWatcher
{
ScanningMode = BluetoothLEScanningMode.Active
};
_watcher.Received += OnAdvertisementReceived;
_watcher.Stopped += OnWatcherStopped;
}
/// <summary>
/// Scan for ITAMAR devices for specified duration
/// </summary>
public async Task<List<DeviceInfo>> ScanAsync(TimeSpan duration, string specificSerial = null)
{
Console.WriteLine($"[Scanner] Starting BLE scan for {duration.TotalSeconds} seconds...");
lock (_lock)
{
_discoveredDevices.Clear();
_scanCompletionSource = new TaskCompletionSource<List<DeviceInfo>>();
}
_watcher.Start();
// Wait for scan duration
await Task.Delay(duration);
_watcher.Stop();
// Wait for stopped event
var devices = await _scanCompletionSource.Task;
// Filter by specific serial if provided
if (!string.IsNullOrEmpty(specificSerial))
{
devices = devices.Where(d => d.SerialNumber == specificSerial).ToList();
}
Console.WriteLine($"[Scanner] Scan complete. Found {devices.Count} ITAMAR device(s).");
return devices;
}
private void OnAdvertisementReceived(BluetoothLEAdvertisementWatcher sender, BluetoothLEAdvertisementReceivedEventArgs args)
{
try
{
// Try to get device name from advertisement
var localName = args.Advertisement.LocalName;
// If not in advertisement, try to get from DeviceInformation
if (string.IsNullOrEmpty(localName))
{
// This requires async but we're in event handler, so we skip for now
return;
}
// Check if this is an ITAMAR device
if (!localName.StartsWith(WatchPatProtocol.DeviceNamePrefix))
return;
var address = args.BluetoothAddress;
lock (_lock)
{
if (_discoveredDevices.ContainsKey(address))
{
// Update existing device
_discoveredDevices[address].SignalStrength = args.RawSignalStrengthInDBm;
_discoveredDevices[address].LastSeen = DateTime.Now;
}
else
{
// Parse serial number
var serialNumber = WatchPatProtocol.ParseSerialNumber(localName);
if (serialNumber == null)
{
Console.WriteLine($"[Scanner] Invalid device name format: {localName}");
return;
}
// Check if it's a new device (ends with 'N')
bool isNew = localName.EndsWith(WatchPatProtocol.DeviceNameSuffixNew);
var deviceInfo = new DeviceInfo
{
Name = localName,
SerialNumber = serialNumber,
BluetoothAddress = address,
SignalStrength = args.RawSignalStrengthInDBm,
IsNew = isNew,
LastSeen = DateTime.Now
};
_discoveredDevices[address] = deviceInfo;
Console.WriteLine($"[Scanner] Found device: {localName} (S/N: {serialNumber}, RSSI: {args.RawSignalStrengthInDBm} dBm, New: {isNew})");
// Notify listeners
DeviceDiscovered?.Invoke(this, deviceInfo);
}
}
}
catch (Exception ex)
{
Console.WriteLine($"[Scanner] Error processing advertisement: {ex.Message}");
}
}
private void OnWatcherStopped(BluetoothLEAdvertisementWatcher sender, BluetoothLEAdvertisementWatcherStoppedEventArgs args)
{
Console.WriteLine($"[Scanner] Watcher stopped. Status: {args.Error}");
lock (_lock)
{
var devices = _discoveredDevices.Values.ToList();
_scanCompletionSource?.TrySetResult(devices);
}
}
/// <summary>
/// Get device by Bluetooth address
/// </summary>
public async Task<BluetoothLEDevice> GetDeviceAsync(ulong bluetoothAddress)
{
try
{
Console.WriteLine($"[Scanner] Getting device for address: {bluetoothAddress:X}");
var device = await BluetoothLEDevice.FromBluetoothAddressAsync(bluetoothAddress);
if (device == null)
{
Console.WriteLine($"[Scanner] Failed to get device.");
return null;
}
Console.WriteLine($"[Scanner] Device retrieved: {device.Name}");
return device;
}
catch (Exception ex)
{
Console.WriteLine($"[Scanner] Error getting device: {ex.Message}");
return null;
}
}
public void Dispose()
{
if (_watcher != null)
{
_watcher.Stop();
_watcher.Received -= OnAdvertisementReceived;
_watcher.Stopped -= OnWatcherStopped;
}
}
}