-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathPeripheral.cpp
More file actions
311 lines (262 loc) · 12.5 KB
/
Copy pathPeripheral.cpp
File metadata and controls
311 lines (262 loc) · 12.5 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
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
#include "pch.h"
#include "Systemic/BluetoothLE/Peripheral.h"
#include "Systemic/BluetoothLE/Service.h"
#include "Systemic/BluetoothLE/Characteristic.h"
using namespace winrt::Windows::Devices::Bluetooth;
using namespace winrt::Windows::Devices::Bluetooth::GenericAttributeProfile;
namespace Systemic::BluetoothLE
{
namespace
{
// Converts a WinRT GattCommunicationStatus to a ConnectionEventReason
inline ConnectionEventReason toReason(GattCommunicationStatus gattStatus)
{
switch (gattStatus)
{
case GattCommunicationStatus::Success:
return ConnectionEventReason::Success;
case GattCommunicationStatus::Unreachable:
return ConnectionEventReason::Timeout;
default:
assert(false);
return ConnectionEventReason::Unknown;
}
}
// Converts a ConnectionEventReason to a BleRequestStatus
inline BleRequestStatus toRequestStatus(ConnectionEventReason reason)
{
switch (reason)
{
case ConnectionEventReason::Success:
return BleRequestStatus::Success;
case ConnectionEventReason::NotSupported:
return BleRequestStatus::NotSupported;
case ConnectionEventReason::Timeout:
return BleRequestStatus::Timeout;
case ConnectionEventReason::Canceled:
return BleRequestStatus::Canceled;
default:
return BleRequestStatus::Error;
}
}
}
std::future<BleRequestStatus> Peripheral::connectAsync(
std::vector<winrt::guid> requiredServices /*= std::vector<winrt::guid>{}*/,
bool maintainConnection /*= false*/)
{
// TODO return error code => GattProtocolError
size_t connectCounter; // Initialized in the block bellow
{
std::lock_guard lock{ _connectOpMtx };
if (_isReady)
{
co_return BleRequestStatus::Success;
}
if (_connecting)
{
// TODO instead wait for other connection call to succeed
co_return BleRequestStatus::InvalidCall;
}
// New connect session
connectCounter = ++_connectCounter;
// Flag ourselves as connecting
_connecting = true;
// We're going to start connecting
_connectionEventsQueue.emplace_back(ConnectionEvent::Connecting, ConnectionEventReason::Success);
}
BleRequestStatus result = BleRequestStatus::Canceled;
try
{
// Move to background thread to avoid blocking itself on re-entrant calls
// (i.e. when try to connect on getting a connection failure event from a previous connection attempt)
co_await winrt::resume_background();
// Notify "connecting" event
notifyQueuedConnectionEvents();
// Get the device and a session object
// Those 2 requests will succeed as long as the device was previously scanned,
// even if it's presently not reachable
auto device = co_await BluetoothLEDevice::FromBluetoothAddressAsync(_address);
GattSession session = nullptr;
if ((connectCounter == _connectCounter) && device)
{
session = co_await GattSession::FromDeviceIdAsync(device.BluetoothDeviceId());
}
// Those variables track the state of the connection process
GattCommunicationStatus gattStatus = GattCommunicationStatus::Success;
bool ownsSession = false;
bool missingServices = false;
std::vector<std::shared_ptr<Service>> services{};
if ((connectCounter == _connectCounter) && session)
{
// We're connected and now need to retrieve the list of services
// This request might take a long time (up to 18 seconds) if the device is not reachable
// TODO use GetGattServicesForUuidAsync() + cache mode
auto servicesResult = co_await device.GetGattServicesAsync(BluetoothCacheMode::Uncached);
gattStatus = servicesResult.Status();
if ((connectCounter == _connectCounter) && (gattStatus == GattCommunicationStatus::Success))
{
std::lock_guard lock{ _connectOpMtx };
// See if we can assign this device and session
if (connectCounter == _connectCounter)
{
assert(!_device);
_device = device;
_session = session;
_connectionStatusChangedToken = _device.ConnectionStatusChanged({ this, &Peripheral::onDeviceConnectionStatusChanged });
ownsSession = true;
_connectionEventsQueue.emplace_back(ConnectionEvent::Connected, ConnectionEventReason::Success);
}
}
if (ownsSession)
{
// If true, it will auto-reconnect to a lost device as soon it's available again
session.MaintainConnection(maintainConnection);
auto gattServices = servicesResult.Services();
bool hasRequiredServices = requiredServices.size() > 0;
// If no service is required, skip checking for missing services
if (hasRequiredServices)
{
// Iterate through services to make sure we have all the requested ones
std::vector<winrt::guid> servicesUuids{};
servicesUuids.reserve(gattServices.Size());
for (auto service : gattServices)
{
servicesUuids.emplace_back(service.Uuid());
}
missingServices = !Internal::isSubset(requiredServices, std::move(servicesUuids));
}
// If all services are accounted for, get their characteristics
if (!missingServices)
{
services.reserve(gattServices.Size());
std::unordered_map<winrt::guid, std::vector<std::shared_ptr<Characteristic>>> characteristics{};
for (auto service : gattServices)
{
// TODO cache mode
GattCharacteristicsResult characteristicsResult = nullptr;
try
{
// Got an exception once, may be caused by having the device disconnected...
characteristicsResult = co_await service.GetCharacteristicsAsync(BluetoothCacheMode::Uncached);
}
catch (const winrt::hresult_error&)
{
gattStatus = GattCommunicationStatus::AccessDenied;
break;
}
gattStatus = characteristicsResult.Status();
if ((connectCounter != _connectCounter) || (gattStatus != GattCommunicationStatus::Success))
{
break;
}
for (auto characteristic : characteristicsResult.Characteristics())
{
auto it = characteristics.try_emplace(characteristic.Uuid()); // , std::vector<std::shared_ptr<Characteristic>>{}
it.first->second.emplace_back(new Characteristic(characteristic));
}
services.emplace_back(new Service{ shared_from_this(), service, characteristics });
characteristics.clear();
}
}
}
}
//
// Almost done, check current state and finalize
//
std::lock_guard lock{ _connectOpMtx };
if (connectCounter == _connectCounter)
{
// If not canceled, the only cause of failures are a null session missing services or a GATT error
auto reason = (session == nullptr) ? ConnectionEventReason::Unknown :
(missingServices ? ConnectionEventReason::NotSupported : toReason(gattStatus));
if (reason == ConnectionEventReason::Success)
{
assert(_device == device);
result = BleRequestStatus::Success;
_services.reserve(services.size());
for (auto& s : services)
{
_services.emplace(s->uuid(), s);
}
_isReady = true;
_connectionEventsQueue.emplace_back(ConnectionEvent::Ready, ConnectionEventReason::Success);
}
else
{
// TODO check if BLE adapter is enabled
//if (!bleApdater.isOn())
//{
// reason = ConnectionEventReason::AdapterOff;
//}
result = toRequestStatus(reason);
assert(result != BleRequestStatus::Success);
if (ownsSession)
{
// It's OK to call disconnect while holding the lock since we have a copy
// of the current device and session, so their destruction won't happen
// in internalDisconnect() but in this method when they go out of scope
// and after the lock has been released
internalDisconnect(reason);
}
else
{
_connectionEventsQueue.emplace_back(ConnectionEvent::FailedToConnect, reason);
}
}
}
//else => don't do anything if canceled, as internalDisconnect() has already been called
_connecting = false;
// Lock is released first, then device and session are destroy here
// if there were not assigned to member variables
}
catch (...)
{
// TODO disconnect
std::lock_guard lock{ _connectOpMtx };
_connecting = false;
throw;
}
notifyQueuedConnectionEvents();
co_return result;
}
void Peripheral::internalDisconnect(ConnectionEventReason reason, bool fromDevice)
{
BluetoothLEDevice device{ nullptr };
GattSession session{ nullptr };
std::vector<std::shared_ptr<Service>> services{};
std::lock_guard lock{ _connectOpMtx };
// Cancel any on-going connect operation
++_connectCounter;
// Nothing to do if no device
if (!_device) return;
assert(_session != nullptr);
// Don't remove device as want it to reconnect automatically
if (fromDevice && (_session.MaintainConnection())) return;
if (!fromDevice)
{
// Notify that we are disconnecting
_connectionEventsQueue.emplace_back(ConnectionEvent::Disconnecting, ConnectionEventReason::Success);
}
// Also notify of disconnection as we won't get a WinRT event
// since we have to destroy the device to force a disconnection
_connectionEventsQueue.emplace_back(ConnectionEvent::Disconnected, reason);
// Unhook from event before destroying device
_device.ConnectionStatusChanged(_connectionStatusChangedToken);
// Copy members
device = _device;
session = _session;
services.reserve(_services.size());
for (auto& [_, s] : _services)
{
services.emplace_back(s);
}
// Clear members
_isReady = false;
_services.clear();
_session = nullptr;
_device = nullptr;
// Lock is released first, then device and session are destroy here
// Any callback to user code will see an empty services list, no session and no device
// TODO in some circumstances, destroying the session+device may block for 5 seconds => spawn a thread?
}
}