Qt
Internal/Contributor docs for the Qt SDK. Note: These are NOT official API docs; those are found at https://doc.qt.io/
Loading...
Searching...
No Matches
btcentralmanager.mm
Go to the documentation of this file.
1// Copyright (C) 2022 The Qt Company Ltd.
2// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
3
8#include "btnotifier_p.h"
9
10#include <QtCore/qloggingcategory.h>
11#include <QtCore/qdebug.h>
12#include <QtCore/qmap.h>
13
14#include <algorithm>
15#include <vector>
16#include <limits>
17
18Q_DECLARE_METATYPE(QLowEnergyHandle)
19
20QT_BEGIN_NAMESPACE
21
22namespace DarwinBluetooth {
23
25{
26 // Identify, how many characteristics/descriptors we have on a given service,
27 // +1 for the service itself.
28 // No checks if NSUInteger is big enough :)
29 // Let's assume such number of entries is not possible :)
30
31 Q_ASSERT_X(service, Q_FUNC_INFO, "invalid service (nil)");
32
34
35 NSArray *const cs = service.characteristics;
36 if (!cs || !cs.count)
37 return 1;
38
39 NSUInteger n = 1 + cs.count;
40 for (CBCharacteristic *c in cs) {
41 NSArray *const ds = c.descriptors;
42 if (ds)
43 n += ds.count;
44 }
45
46 return n;
47}
48
50{
51 // For now we do not provide details, since nobody is using this NSError
52 // after all (except callbacks checking if an operation was successful
53 // or not).
54 Q_ASSERT(type != OperationTimeout::none);
55 Q_UNUSED(type);
56 NSError *nsError = [[NSError alloc] initWithDomain:CBErrorDomain
57 code:CBErrorOperationCancelled
58 userInfo:nil];
59 return ObjCStrongReference<NSError>(nsError, RetainPolicy::noInitialRetain);
60}
61
62auto qt_find_watchdog(const std::vector<GCDTimer> &watchdogs, id object, OperationTimeout type)
63{
64 return std::find_if(watchdogs.begin(), watchdogs.end(), [object, type](const GCDTimer &other){
65 return [other objectUnderWatch] == object && [other timeoutType] == type;});
66}
67
68} // namespace DarwinBluetooth
69
70QT_END_NAMESPACE
71
72QT_USE_NAMESPACE
73
74@interface DarwinBTCentralManager (PrivateAPI)
75
76- (void)watchAfter:(id)object timeout:(DarwinBluetooth::OperationTimeout)type;
77- (bool)objectIsUnderWatch:(id)object operation:(DarwinBluetooth::OperationTimeout)type;
78- (void)stopWatchingAfter:(id)object operation:(DarwinBluetooth::OperationTimeout)type;
79- (void)stopWatchers;
80- (void)retrievePeripheralAndConnect;
81- (void)connectToPeripheral;
82- (void)discoverIncludedServices;
83- (void)readCharacteristics:(CBService *)service;
84- (void)serviceDetailsDiscoveryFinished:(CBService *)service;
85- (void)performNextRequest;
86- (void)performNextReadRequest;
87- (void)performNextWriteRequest;
88
89// Aux. functions.
90- (CBService *)serviceForUUID:(const QBluetoothUuid &)qtUuid;
91- (CBCharacteristic *)nextCharacteristicForService:(CBService*)service
92 startingFrom:(CBCharacteristic *)from;
93- (CBCharacteristic *)nextCharacteristicForService:(CBService*)service
94 startingFrom:(CBCharacteristic *)from
95 withProperties:(CBCharacteristicProperties)properties;
96- (CBDescriptor *)nextDescriptorForCharacteristic:(CBCharacteristic *)characteristic
97 startingFrom:(CBDescriptor *)descriptor;
98- (CBDescriptor *)descriptor:(const QBluetoothUuid &)dUuid
99 forCharacteristic:(CBCharacteristic *)ch;
100- (bool)cacheWriteValue:(const QByteArray &)value for:(NSObject *)obj;
101- (void)handleReadWriteError:(NSError *)error;
102- (void)reset;
103- (void)releasePeripheral;
104
105@end
106
107using DiscoveryMode = QLowEnergyService::DiscoveryMode;
108
109@implementation DarwinBTCentralManager
110{
111@private
112 CBCentralManager *manager;
113 DarwinBluetooth::CentralManagerState managerState;
114 bool disconnectPending;
115
116 QBluetoothUuid deviceUuid;
117
118 DarwinBluetooth::LECBManagerNotifier *notifier;
119
120 // Quite a verbose service discovery machinery
121 // (a "graph traversal").
122 DarwinBluetooth::ObjCStrongReference<NSMutableArray> servicesToVisit;
123 // The service we're discovering now (included services discovery):
124 NSUInteger currentService;
125 // Included services, we'll iterate through at the end of 'servicesToVisit':
126 DarwinBluetooth::ObjCStrongReference<NSMutableArray> servicesToVisitNext;
127 // We'd like to avoid loops in a services' topology:
128 DarwinBluetooth::ObjCStrongReference<NSMutableSet> visitedServices;
129
130 QMap<QBluetoothUuid, DiscoveryMode> servicesToDiscoverDetails;
131
132 DarwinBluetooth::ServiceHash serviceMap;
133 DarwinBluetooth::CharHash charMap;
134 DarwinBluetooth::DescHash descMap;
135
136 QLowEnergyHandle lastValidHandle;
137
138 bool requestPending;
139 DarwinBluetooth::RequestQueue requests;
140 QLowEnergyHandle currentReadHandle;
141
142 DarwinBluetooth::ValueHash valuesToWrite;
143
144 qint64 timeoutMS;
145 std::vector<DarwinBluetooth::GCDTimer> timeoutWatchdogs;
146
147 CBPeripheral *peripheral;
148 int lastKnownMtu;
149}
150
151- (id)initWith:(DarwinBluetooth::LECBManagerNotifier *)aNotifier
152{
153 using namespace DarwinBluetooth;
154
155 if (self = [super init]) {
156 manager = nil;
157 managerState = CentralManagerIdle;
158 disconnectPending = false;
159 peripheral = nil;
160 notifier = aNotifier;
161 currentService = 0;
162 lastValidHandle = 0;
163 requestPending = false;
164 currentReadHandle = 0;
165
166 if (Q_UNLIKELY(!qEnvironmentVariableIsEmpty("BLUETOOTH_GATT_TIMEOUT"))) {
167 bool ok = false;
168 const int value = qEnvironmentVariableIntValue("BLUETOOTH_GATT_TIMEOUT", &ok);
169 if (ok && value >= 0)
170 timeoutMS = value;
171 }
172
173 if (!timeoutMS)
174 timeoutMS = 20000;
175
176 lastKnownMtu = defaultMtu;
177 }
178
179 return self;
180}
181
182- (void)dealloc
183{
184 // In the past I had a 'transient delegate': I've seen some crashes
185 // while deleting a manager _before_ its state updated.
186 // Strangely enough, I can not reproduce this anymore, so this
187 // part is simplified now. To be investigated though.
188
189 visitedServices.reset();
190 servicesToVisit.reset();
191 servicesToVisitNext.reset();
192
193 [manager setDelegate:nil];
194 [manager release];
195
196 [peripheral setDelegate:nil];
197 [peripheral release];
198
199 if (notifier)
200 notifier->deleteLater();
201
202 [self stopWatchers];
203 [super dealloc];
204}
205
206- (CBPeripheral *)peripheral
207{
208 return peripheral;
209}
210
211- (void)watchAfter:(id)object timeout:(DarwinBluetooth::OperationTimeout)type
212{
213 using namespace DarwinBluetooth;
214
215 GCDTimer newWatcher([[DarwinBTGCDTimer alloc] initWithDelegate:self], RetainPolicy::noInitialRetain);
216 [newWatcher watchAfter:object withTimeoutType:type];
217 timeoutWatchdogs.push_back(newWatcher);
218 [newWatcher startWithTimeout:timeoutMS step:200];
219}
220
221- (bool)objectIsUnderWatch:(id)object operation:(DarwinBluetooth::OperationTimeout)type
222{
223 return DarwinBluetooth::qt_find_watchdog(timeoutWatchdogs, object, type) != timeoutWatchdogs.end();
224}
225
226- (void)stopWatchingAfter:(id)object operation:(DarwinBluetooth::OperationTimeout)type
227{
228 auto pos = DarwinBluetooth::qt_find_watchdog(timeoutWatchdogs, object, type);
229 if (pos != timeoutWatchdogs.end()) {
230 [*pos cancelTimer];
231 timeoutWatchdogs.erase(pos);
232 }
233}
234
235- (void)stopWatchers
236{
237 for (auto &watchdog : timeoutWatchdogs)
238 [watchdog cancelTimer];
239 timeoutWatchdogs.clear();
240}
241
242- (void)timeout:(id)sender
243{
244 Q_UNUSED(sender);
245
246 using namespace DarwinBluetooth;
247
248 DarwinBTGCDTimer *watcher = static_cast<DarwinBTGCDTimer *>(sender);
249 id cbObject = [watcher objectUnderWatch];
250 const OperationTimeout type = [watcher timeoutType];
251
252 Q_ASSERT([self objectIsUnderWatch:cbObject operation:type]);
253
254 NSLog(@"Timeout caused by: %@", cbObject);
255
256 // Note that after this switch the 'watcher' is released (we don't
257 // own it anymore), though GCD is probably still holding a reference.
258 const ObjCStrongReference<NSError> nsError(qt_timeoutNSError(type));
259 switch (type) {
260 case OperationTimeout::serviceDiscovery:
261 qCWarning(QT_BT_DARWIN, "Timeout in services discovery");
262 [self peripheral:peripheral didDiscoverServices:nsError];
263 break;
264 case OperationTimeout::includedServicesDiscovery:
265 qCWarning(QT_BT_DARWIN, "Timeout in included services discovery");
266 [self peripheral:peripheral didDiscoverIncludedServicesForService:cbObject error:nsError];
267 break;
268 case OperationTimeout::characteristicsDiscovery:
269 qCWarning(QT_BT_DARWIN, "Timeout in characteristics discovery");
270 [self peripheral:peripheral didDiscoverCharacteristicsForService:cbObject error:nsError];
271 break;
272 case OperationTimeout::characteristicRead:
273 qCWarning(QT_BT_DARWIN, "Timeout while reading a characteristic");
274 [self peripheral:peripheral didUpdateValueForCharacteristic:cbObject error:nsError];
275 break;
276 case OperationTimeout::descriptorsDiscovery:
277 qCWarning(QT_BT_DARWIN, "Timeout in descriptors discovery");
278 [self peripheral:peripheral didDiscoverDescriptorsForCharacteristic:cbObject error:nsError];
279 break;
280 case OperationTimeout::descriptorRead:
281 qCWarning(QT_BT_DARWIN, "Timeout while reading a descriptor");
282 [self peripheral:peripheral didUpdateValueForDescriptor:cbObject error:nsError];
283 break;
284 case OperationTimeout::characteristicWrite:
285 qCWarning(QT_BT_DARWIN, "Timeout while writing a characteristic with response");
286 [self peripheral:peripheral didWriteValueForCharacteristic:cbObject error:nsError];
287 default:;
288 }
289}
290
291- (void)connectToDevice:(const QBluetoothUuid &)aDeviceUuid
292{
293 disconnectPending = false; // Cancel the previous disconnect if any.
294 deviceUuid = aDeviceUuid;
295
296 if (!manager) {
297 // The first time we try to connect, no manager created yet,
298 // no status update received.
299 if (const dispatch_queue_t leQueue = DarwinBluetooth::qt_LE_queue()) {
300 managerState = DarwinBluetooth::CentralManagerUpdating;
301 manager = [[CBCentralManager alloc] initWithDelegate:self queue:leQueue];
302 }
303
304 if (!manager) {
305 managerState = DarwinBluetooth::CentralManagerIdle;
306 qCWarning(QT_BT_DARWIN) << "failed to allocate a central manager";
307 if (notifier)
308 emit notifier->CBManagerError(QLowEnergyController::ConnectionError);
309 }
310 } else if (managerState != DarwinBluetooth::CentralManagerUpdating) {
311 [self retrievePeripheralAndConnect];
312 }
313}
314
315- (void)retrievePeripheralAndConnect
316{
317 Q_ASSERT_X(manager, Q_FUNC_INFO, "invalid central manager (nil)");
318 Q_ASSERT_X(managerState == DarwinBluetooth::CentralManagerIdle,
319 Q_FUNC_INFO, "invalid state");
320
321 if ([self isConnected]) {
322 qCDebug(QT_BT_DARWIN) << "already connected";
323 if (notifier)
324 emit notifier->connected();
325 return;
326 } else if (peripheral) {
327 // Was retrieved already, but not connected
328 // or disconnected.
329 [self connectToPeripheral];
330 return;
331 }
332
333 using namespace DarwinBluetooth;
334
335 // Retrieve a peripheral first ...
336 const ObjCScopedPointer<NSMutableArray> uuids([[NSMutableArray alloc] init], RetainPolicy::noInitialRetain);
337 if (!uuids) {
338 qCWarning(QT_BT_DARWIN) << "failed to allocate identifiers";
339 if (notifier)
340 emit notifier->CBManagerError(QLowEnergyController::ConnectionError);
341 return;
342 }
343
344
345 const QUuid::Id128Bytes qtUuidData(deviceUuid.toBytes());
346 uuid_t uuidData = {};
347 std::copy(qtUuidData.data, qtUuidData.data + 16, uuidData);
348 const ObjCScopedPointer<NSUUID> nsUuid([[NSUUID alloc] initWithUUIDBytes:uuidData], RetainPolicy::noInitialRetain);
349 if (!nsUuid) {
350 qCWarning(QT_BT_DARWIN) << "failed to allocate NSUUID identifier";
351 if (notifier)
352 emit notifier->CBManagerError(QLowEnergyController::ConnectionError);
353 return;
354 }
355
356 [uuids addObject:nsUuid];
357 // With the latest CoreBluetooth, we can synchronously retrieve peripherals:
359 NSArray *const peripherals = [manager retrievePeripheralsWithIdentifiers:uuids];
360 if (!peripherals || peripherals.count != 1) {
361 qCWarning(QT_BT_DARWIN) << "failed to retrieve a peripheral";
362 if (notifier)
363 emit notifier->CBManagerError(QLowEnergyController::UnknownRemoteDeviceError);
364 return;
365 }
366
367 peripheral = [static_cast<CBPeripheral *>([peripherals objectAtIndex:0]) retain];
368 [self connectToPeripheral];
369}
370
371- (void)connectToPeripheral
372{
373 using namespace DarwinBluetooth;
374
375 Q_ASSERT_X(manager, Q_FUNC_INFO, "invalid central manager (nil)");
376 Q_ASSERT_X(peripheral, Q_FUNC_INFO, "invalid peripheral (nil)");
377 Q_ASSERT_X(managerState == CentralManagerIdle, Q_FUNC_INFO, "invalid state");
378
379 // The state is still the same - connecting.
380 if ([self isConnected]) {
381 qCDebug(QT_BT_DARWIN) << "already connected";
382 if (notifier)
383 emit notifier->connected();
384 } else {
385 [self setMtu:defaultMtu];
386 qCDebug(QT_BT_DARWIN) << "trying to connect";
387 managerState = CentralManagerConnecting;
388 [manager connectPeripheral:peripheral options:nil];
389 }
390}
391
392- (bool)isConnected
393{
394 if (!peripheral)
395 return false;
396
397 return peripheral.state == CBPeripheralStateConnected;
398}
399
400- (void)disconnectFromDevice
401{
402 [self reset];
403
404 if (managerState == DarwinBluetooth::CentralManagerUpdating) {
405 disconnectPending = true; // this is for 'didUpdate' method.
406 if (notifier) {
407 // We were waiting for the first update
408 // with 'PoweredOn' status, when suddenly got disconnected called.
409 // Since we have not attempted to connect yet, emit now.
410 // Note: we do not change the state, since we still maybe interested
411 // in the status update before the next connect attempt.
412 emit notifier->disconnected();
413 }
414 } else {
415 disconnectPending = false;
416 if ([self isConnected])
417 managerState = DarwinBluetooth::CentralManagerDisconnecting;
418 else
419 managerState = DarwinBluetooth::CentralManagerIdle;
420
421 // We have to call -cancelPeripheralConnection: even
422 // if not connected (to cancel a pending connect attempt).
423 // Unfortunately, didDisconnect callback is not always called
424 // (despite of Apple's docs saying it _must_ be).
425 if (peripheral)
426 [manager cancelPeripheralConnection:peripheral];
427 }
428}
429
430- (void)discoverServices
431{
432 using namespace DarwinBluetooth;
433
434 Q_ASSERT_X(peripheral, Q_FUNC_INFO, "invalid peripheral (nil)");
435 Q_ASSERT_X(managerState == CentralManagerIdle, Q_FUNC_INFO, "invalid state");
436
437 // From Apple's docs:
438 //
439 //"If the servicesUUIDs parameter is nil, all the available
440 //services of the peripheral are returned; setting the
441 //parameter to nil is considerably slower and is not recommended."
442 //
443 // ... but we'd like to have them all:
444 managerState = CentralManagerDiscovering;
445 [self watchAfter:peripheral timeout:OperationTimeout::serviceDiscovery];
446 [peripheral discoverServices:nil];
447}
448
449- (void)discoverIncludedServices
450{
451 using namespace DarwinBluetooth;
452
453 Q_ASSERT_X(managerState == CentralManagerIdle, Q_FUNC_INFO, "invalid state");
454 Q_ASSERT_X(manager, Q_FUNC_INFO, "invalid manager (nil)");
455 Q_ASSERT_X(peripheral, Q_FUNC_INFO, "invalid peripheral (nil)");
456
458
459 NSArray *const services = peripheral.services;
460 if (!services || !services.count) {
461 // A peripheral without any services at all.
462 if (notifier)
463 emit notifier->serviceDiscoveryFinished();
464 } else {
465 // 'reset' also calls retain on a parameter.
466 servicesToVisitNext.reset();
467 servicesToVisit.reset([NSMutableArray arrayWithArray:services], RetainPolicy::doInitialRetain);
468 currentService = 0;
469 visitedServices.reset([NSMutableSet setWithCapacity:peripheral.services.count], RetainPolicy::doInitialRetain);
470
471 CBService *const s = [services objectAtIndex:currentService];
472 [visitedServices addObject:s];
473 managerState = CentralManagerDiscovering;
474 [self watchAfter:s timeout:OperationTimeout::includedServicesDiscovery];
475 [peripheral discoverIncludedServices:nil forService:s];
476 }
477}
478
479- (void)discoverServiceDetails:(const QBluetoothUuid &)serviceUuid
480 readValues:(bool) read
481{
482 // This function does not change 'managerState', since it
483 // can be called concurrently (not waiting for the previous
484 // discovery to finish).
485
486 using namespace DarwinBluetooth;
487
488 Q_ASSERT_X(managerState != CentralManagerUpdating, Q_FUNC_INFO, "invalid state");
489 Q_ASSERT_X(!serviceUuid.isNull(), Q_FUNC_INFO, "invalid service UUID");
490 Q_ASSERT_X(peripheral, Q_FUNC_INFO, "invalid peripheral (nil)");
491
492 if (servicesToDiscoverDetails.contains(serviceUuid)) {
493 qCWarning(QT_BT_DARWIN) << "already discovering for"
494 << serviceUuid;
495 return;
496 }
497
499
500 if (CBService *const service = [self serviceForUUID:serviceUuid]) {
501 const auto mode = read ? DiscoveryMode::FullDiscovery : DiscoveryMode::SkipValueDiscovery;
502 servicesToDiscoverDetails[serviceUuid] = mode;
503 [self watchAfter:service timeout:OperationTimeout::characteristicsDiscovery];
504 [peripheral discoverCharacteristics:nil forService:service];
505 return;
506 }
507
508 qCWarning(QT_BT_DARWIN) << "unknown service uuid"
509 << serviceUuid;
510
511 if (notifier)
512 emit notifier->CBManagerError(serviceUuid, QLowEnergyService::UnknownError);
513}
514
515- (void)readCharacteristics:(CBService *)service
516{
517 // This method does not change 'managerState', we can
518 // have several 'detail discoveries' active.
519 Q_ASSERT_X(service, Q_FUNC_INFO, "invalid service (nil)");
520
521 using namespace DarwinBluetooth;
522
524
525 Q_ASSERT_X(managerState != CentralManagerUpdating, Q_FUNC_INFO, "invalid state");
526 Q_ASSERT_X(manager, Q_FUNC_INFO, "invalid manager (nil)");
527 Q_ASSERT_X(peripheral, Q_FUNC_INFO, "invalid peripheral (nil)");
528
529 if (!service.characteristics || !service.characteristics.count)
530 return [self serviceDetailsDiscoveryFinished:service];
531
532 NSArray *const cs = service.characteristics;
533 for (CBCharacteristic *c in cs) {
534 if (c.properties & CBCharacteristicPropertyRead) {
535 [self watchAfter:c timeout:OperationTimeout::characteristicRead];
536 return [peripheral readValueForCharacteristic:c];
537 }
538 }
539
540 // No readable properties? Discover descriptors then:
541 [self discoverDescriptors:service];
542}
543
544- (void)discoverDescriptors:(CBService *)service
545{
546 // This method does not change 'managerState', we can have
547 // several discoveries active.
548 Q_ASSERT_X(service, Q_FUNC_INFO, "invalid service (nil)");
549
550 using namespace DarwinBluetooth;
551
553
554 Q_ASSERT_X(managerState != CentralManagerUpdating,
555 Q_FUNC_INFO, "invalid state");
556 Q_ASSERT_X(manager, Q_FUNC_INFO, "invalid manager (nil)");
557 Q_ASSERT_X(peripheral, Q_FUNC_INFO, "invalid peripheral (nil)");
558
559 if (!service.characteristics || !service.characteristics.count) {
560 [self serviceDetailsDiscoveryFinished:service];
561 } else {
562 // Start from 0 and continue in the callback.
563 CBCharacteristic *ch = [service.characteristics objectAtIndex:0];
564 [self watchAfter:ch timeout:OperationTimeout::descriptorsDiscovery];
565 [peripheral discoverDescriptorsForCharacteristic:ch];
566 }
567}
568
569- (void)readDescriptors:(CBService *)service
570{
571 using namespace DarwinBluetooth;
572
573 Q_ASSERT_X(service, Q_FUNC_INFO, "invalid service (nil)");
574 Q_ASSERT_X(managerState != CentralManagerUpdating, Q_FUNC_INFO, "invalid state");
575 Q_ASSERT_X(peripheral, Q_FUNC_INFO, "invalid peripheral (nil)");
576
578
579 NSArray *const cs = service.characteristics;
580 // We can never be here if we have no characteristics.
581 Q_ASSERT_X(cs && cs.count, Q_FUNC_INFO, "invalid service");
582 for (CBCharacteristic *c in cs) {
583 if (c.descriptors && c.descriptors.count) {
584 CBDescriptor *desc = [c.descriptors objectAtIndex:0];
585 [self watchAfter:desc timeout:OperationTimeout::descriptorRead];
586 return [peripheral readValueForDescriptor:desc];
587 }
588 }
589
590 // No descriptors to read, done.
591 [self serviceDetailsDiscoveryFinished:service];
592}
593
594- (void)serviceDetailsDiscoveryFinished:(CBService *)service
595{
596 Q_ASSERT_X(service, Q_FUNC_INFO, "invalid service (nil)");
597
598 using namespace DarwinBluetooth;
599
601
602 const QBluetoothUuid serviceUuid(qt_uuid(service.UUID));
603 const bool skipValues = servicesToDiscoverDetails[serviceUuid] == DiscoveryMode::SkipValueDiscovery;
604 servicesToDiscoverDetails.remove(serviceUuid);
605
606 const NSUInteger nHandles = qt_countGATTEntries(service);
607 Q_ASSERT_X(nHandles, Q_FUNC_INFO, "unexpected number of GATT entires");
608
609 const QLowEnergyHandle maxHandle = std::numeric_limits<QLowEnergyHandle>::max();
610 if (nHandles >= maxHandle || lastValidHandle > maxHandle - nHandles) {
611 // Well, that's unlikely :) But we must be sure.
612 qCWarning(QT_BT_DARWIN) << "can not allocate more handles";
613 if (notifier)
614 notifier->CBManagerError(serviceUuid, QLowEnergyService::OperationError);
615 return;
616 }
617
618 // A temporary service object to pass the details.
619 // Set only uuid, characteristics and descriptors (and probably values),
620 // nothing else is needed.
621 QSharedPointer<QLowEnergyServicePrivate> qtService(new QLowEnergyServicePrivate);
622 qtService->uuid = serviceUuid;
623 // We 'register' handles/'CBentities' even if qlowenergycontroller (delegate)
624 // later fails to do this with some error. Otherwise, if we try to implement
625 // rollback/transaction logic interface is getting too ugly/complicated.
626 ++lastValidHandle;
627 serviceMap[lastValidHandle] = service;
628 qtService->startHandle = lastValidHandle;
629
630 NSArray *const cs = service.characteristics;
631 // Now map chars/descriptors and handles.
632 if (cs && cs.count) {
633 QHash<QLowEnergyHandle, QLowEnergyServicePrivate::CharData> charList;
634
635 for (CBCharacteristic *c in cs) {
636 ++lastValidHandle;
637 // Register this characteristic:
638 charMap[lastValidHandle] = c;
639 // Create a Qt's internal characteristic:
640 QLowEnergyServicePrivate::CharData newChar = {};
641 newChar.uuid = qt_uuid(c.UUID);
642 const int cbProps = c.properties & 0xff;
643 newChar.properties = static_cast<QLowEnergyCharacteristic::PropertyTypes>(cbProps);
644 if (!skipValues)
645 newChar.value = qt_bytearray(c.value);
646 newChar.valueHandle = lastValidHandle;
647
648 NSArray *const ds = c.descriptors;
649 if (ds && ds.count) {
650 QHash<QLowEnergyHandle, QLowEnergyServicePrivate::DescData> descList;
651 for (CBDescriptor *d in ds) {
652 // Register this descriptor:
653 ++lastValidHandle;
654 descMap[lastValidHandle] = d;
655 // Create a Qt's internal descriptor:
656 QLowEnergyServicePrivate::DescData newDesc = {};
657 newDesc.uuid = qt_uuid(d.UUID);
658 newDesc.value = qt_bytearray(static_cast<NSObject *>(d.value));
659 descList[lastValidHandle] = newDesc;
660 // Check, if it's client characteristic configuration descriptor:
661 if (newDesc.uuid == QBluetoothUuid::DescriptorType::ClientCharacteristicConfiguration) {
662 if (newDesc.value.size() && (newDesc.value[0] & 3))
663 [peripheral setNotifyValue:YES forCharacteristic:c];
664 }
665 }
666
667 newChar.descriptorList = descList;
668 }
669
670 charList[newChar.valueHandle] = newChar;
671 }
672
673 qtService->characteristicList = charList;
674 }
675
676 qtService->endHandle = lastValidHandle;
677
678 if (notifier)
679 emit notifier->serviceDetailsDiscoveryFinished(qtService);
680}
681
682- (void)performNextRequest
683{
684 using namespace DarwinBluetooth;
685
686 if (requestPending || !requests.size())
687 return;
688
689 switch (requests.head().type) {
690 case LERequest::CharRead:
691 case LERequest::DescRead:
692 return [self performNextReadRequest];
693 case LERequest::CharWrite:
694 case LERequest::DescWrite:
695 case LERequest::ClientConfiguration:
696 return [self performNextWriteRequest];
697 default:
698 // Should never happen.
699 Q_ASSERT(0);
700 }
701}
702
703- (void)performNextReadRequest
704{
705 using namespace DarwinBluetooth;
706
707 Q_ASSERT_X(peripheral, Q_FUNC_INFO, "invalid peripheral (nil)");
708 Q_ASSERT_X(!requestPending, Q_FUNC_INFO, "processing another request");
709 Q_ASSERT_X(requests.size(), Q_FUNC_INFO, "no requests to handle");
710 Q_ASSERT_X(requests.head().type == LERequest::CharRead
711 || requests.head().type == LERequest::DescRead,
712 Q_FUNC_INFO, "not a read request");
713
714 const LERequest request(requests.dequeue());
715 if (request.type == LERequest::CharRead) {
716 if (!charMap.contains(request.handle)) {
717 qCWarning(QT_BT_DARWIN) << "characteristic with handle"
718 << request.handle << "not found";
719 return [self performNextRequest];
720 }
721
722 requestPending = true;
723 currentReadHandle = request.handle;
724 // Timeouts: for now, we do not alert timeoutWatchdog - never had such
725 // bug reports and after all a read timeout can be handled externally.
726 [peripheral readValueForCharacteristic:charMap[request.handle]];
727 } else {
728 if (!descMap.contains(request.handle)) {
729 qCWarning(QT_BT_DARWIN) << "descriptor with handle"
730 << request.handle << "not found";
731 return [self performNextRequest];
732 }
733
734 requestPending = true;
735 currentReadHandle = request.handle;
736 // Timeouts: see the comment above (CharRead).
737 [peripheral readValueForDescriptor:descMap[request.handle]];
738 }
739}
740
741- (void)performNextWriteRequest
742{
743 using namespace DarwinBluetooth;
744
745 Q_ASSERT_X(peripheral, Q_FUNC_INFO, "invalid peripheral (nil)");
746 Q_ASSERT_X(!requestPending, Q_FUNC_INFO, "processing another request");
747 Q_ASSERT_X(requests.size(), Q_FUNC_INFO, "no requests to handle");
748 Q_ASSERT_X(requests.head().type == LERequest::CharWrite
749 || requests.head().type == LERequest::DescWrite
750 || requests.head().type == LERequest::ClientConfiguration,
751 Q_FUNC_INFO, "not a write request");
752
753 const LERequest request(requests.dequeue());
754
755 if (request.type == LERequest::DescWrite) {
756 if (!descMap.contains(request.handle)) {
757 qCWarning(QT_BT_DARWIN) << "handle:" << request.handle
758 << "not found";
759 return [self performNextRequest];
760 }
761
762 CBDescriptor *const descriptor = descMap[request.handle];
763 ObjCStrongReference<NSData> data(data_from_bytearray(request.value));
764 if (!data) {
765 // Even if qtData.size() == 0, we still need NSData object.
766 qCWarning(QT_BT_DARWIN) << "failed to allocate an NSData object";
767 return [self performNextRequest];
768 }
769
770 if (![self cacheWriteValue:request.value for:descriptor])
771 return [self performNextRequest];
772
773 requestPending = true;
774 return [peripheral writeValue:data.data() forDescriptor:descriptor];
775 } else {
776 if (!charMap.contains(request.handle)) {
777 qCWarning(QT_BT_DARWIN) << "characteristic with handle:"
778 << request.handle << "not found";
779 return [self performNextRequest];
780 }
781
782 CBCharacteristic *const characteristic = charMap[request.handle];
783
784 if (request.type == LERequest::ClientConfiguration) {
785 const QBluetoothUuid qtUuid(QBluetoothUuid::DescriptorType::ClientCharacteristicConfiguration);
786 CBDescriptor *const descriptor = [self descriptor:qtUuid forCharacteristic:characteristic];
787 Q_ASSERT_X(descriptor, Q_FUNC_INFO, "no client characteristic "
788 "configuration descriptor found");
789
790 if (![self cacheWriteValue:request.value for:descriptor])
791 return [self performNextRequest];
792
793 bool enable = false;
794 if (request.value.size())
795 enable = request.value[0] & 3;
796
797 requestPending = true;
798 [peripheral setNotifyValue:enable forCharacteristic:characteristic];
799 } else {
800 ObjCStrongReference<NSData> data(data_from_bytearray(request.value));
801 if (!data) {
802 // Even if qtData.size() == 0, we still need NSData object.
803 qCWarning(QT_BT_DARWIN) << "failed to allocate NSData object";
804 return [self performNextRequest];
805 }
806
807 // TODO: check what happens if I'm using NSData with length 0.
808 if (request.withResponse) {
809 if (![self cacheWriteValue:request.value for:characteristic])
810 return [self performNextRequest];
811
812 requestPending = true;
813 [self watchAfter:characteristic timeout:OperationTimeout::characteristicWrite];
814 [peripheral writeValue:data.data() forCharacteristic:characteristic
815 type:CBCharacteristicWriteWithResponse];
816 } else {
817 [peripheral writeValue:data.data() forCharacteristic:characteristic
818 type:CBCharacteristicWriteWithoutResponse];
819 [self performNextRequest];
820 }
821 }
822 }
823}
824
825- (void)setMtu:(int)newMtu
826{
827 if (lastKnownMtu == newMtu)
828 return;
829 lastKnownMtu = newMtu;
830 if (notifier)
831 emit notifier->mtuChanged(newMtu);
832}
833
834- (int)mtu
835{
836 using namespace DarwinBluetooth;
837
838 if (![self isConnected]) {
839 [self setMtu:defaultMtu];
840 return defaultMtu;
841 }
842
843 Q_ASSERT(peripheral);
844 const NSUInteger maxLen = [peripheral maximumWriteValueLengthForType:
845 CBCharacteristicWriteWithoutResponse];
846 if (maxLen > std::numeric_limits<int>::max() - 3)
847 [self setMtu:defaultMtu];
848 else
849 [self setMtu:int(maxLen) + 3];
850
851 return lastKnownMtu;
852}
853
854- (void)readRssi
855{
856 Q_ASSERT([self isConnected]);
857 [peripheral readRSSI];
858}
859
860- (void)setNotifyValue:(const QByteArray &)value
861 forCharacteristic:(QLowEnergyHandle)charHandle
862 onService:(const QBluetoothUuid &)serviceUuid
863{
864 using namespace DarwinBluetooth;
865
866 Q_ASSERT_X(charHandle, Q_FUNC_INFO, "invalid characteristic handle (0)");
867
868 if (!charMap.contains(charHandle)) {
869 qCWarning(QT_BT_DARWIN) << "unknown characteristic handle"
870 << charHandle;
871 if (notifier) {
872 emit notifier->CBManagerError(serviceUuid,
873 QLowEnergyService::DescriptorWriteError);
874 }
875 return;
876 }
877
878 // At the moment we call setNotifyValue _only_ from 'writeDescriptor';
879 // from Qt's API POV it's a descriptor write operation and we must report
880 // it back, so check _now_ that we really have this descriptor.
881 const QBluetoothUuid qtUuid(QBluetoothUuid::DescriptorType::ClientCharacteristicConfiguration);
882 if (![self descriptor:qtUuid forCharacteristic:charMap[charHandle]]) {
883 qCWarning(QT_BT_DARWIN) << "no client characteristic configuration found";
884 if (notifier) {
885 emit notifier->CBManagerError(serviceUuid,
886 QLowEnergyService::DescriptorWriteError);
887 }
888 return;
889 }
890
891 LERequest request;
892 request.type = LERequest::ClientConfiguration;
893 request.handle = charHandle;
894 request.value = value;
895
896 requests.enqueue(request);
897 [self performNextRequest];
898}
899
900- (void)readCharacteristic:(QLowEnergyHandle)charHandle
901 onService:(const QBluetoothUuid &)serviceUuid
902{
903 using namespace DarwinBluetooth;
904
905 Q_ASSERT_X(charHandle, Q_FUNC_INFO, "invalid characteristic handle (0)");
906
908
909 if (!charMap.contains(charHandle)) {
910 qCWarning(QT_BT_DARWIN) << "characteristic:" << charHandle << "not found";
911 if (notifier) {
912 emit notifier->CBManagerError(serviceUuid,
913 QLowEnergyService::CharacteristicReadError);
914
915 }
916 return;
917 }
918
919 LERequest request;
920 request.type = LERequest::CharRead;
921 request.handle = charHandle;
922
923 requests.enqueue(request);
924 [self performNextRequest];
925}
926
927- (void)write:(const QByteArray &)value
928 charHandle:(QLowEnergyHandle)charHandle
929 onService:(const QBluetoothUuid &)serviceUuid
930 withResponse:(bool)withResponse
931{
932 using namespace DarwinBluetooth;
933
934 Q_ASSERT_X(charHandle, Q_FUNC_INFO, "invalid characteristic handle (0)");
935
937
938 if (!charMap.contains(charHandle)) {
939 qCWarning(QT_BT_DARWIN) << "characteristic:" << charHandle << "not found";
940 if (notifier) {
941 emit notifier->CBManagerError(serviceUuid,
942 QLowEnergyService::CharacteristicWriteError);
943 }
944 return;
945 }
946
947 LERequest request;
948 request.type = LERequest::CharWrite;
949 request.withResponse = withResponse;
950 request.handle = charHandle;
951 request.value = value;
952
953 requests.enqueue(request);
954 [self performNextRequest];
955}
956
957- (void)readDescriptor:(QLowEnergyHandle)descHandle
958 onService:(const QBluetoothUuid &)serviceUuid
959{
960 using namespace DarwinBluetooth;
961
962 Q_ASSERT_X(descHandle, Q_FUNC_INFO, "invalid descriptor handle (0)");
963
964 if (!descMap.contains(descHandle)) {
965 qCWarning(QT_BT_DARWIN) << "handle:" << descHandle << "not found";
966 if (notifier) {
967 emit notifier->CBManagerError(serviceUuid,
968 QLowEnergyService::DescriptorReadError);
969 }
970 return;
971 }
972
973 LERequest request;
974 request.type = LERequest::DescRead;
975 request.handle = descHandle;
976
977 requests.enqueue(request);
978 [self performNextRequest];
979}
980
981- (void)write:(const QByteArray &)value
982 descHandle:(QLowEnergyHandle)descHandle
983 onService:(const QBluetoothUuid &)serviceUuid
984{
985 using namespace DarwinBluetooth;
986
987 Q_ASSERT_X(descHandle, Q_FUNC_INFO, "invalid descriptor handle (0)");
988
989 if (!descMap.contains(descHandle)) {
990 qCWarning(QT_BT_DARWIN) << "handle:" << descHandle << "not found";
991 if (notifier) {
992 emit notifier->CBManagerError(serviceUuid,
993 QLowEnergyService::DescriptorWriteError);
994 }
995 return;
996 }
997
998 LERequest request;
999 request.type = LERequest::DescWrite;
1000 request.handle = descHandle;
1001 request.value = value;
1002
1003 requests.enqueue(request);
1004 [self performNextRequest];
1005}
1006
1007// Aux. methods:
1008
1009- (CBService *)serviceForUUID:(const QBluetoothUuid &)qtUuid
1010{
1011 using namespace DarwinBluetooth;
1012
1013 Q_ASSERT_X(!qtUuid.isNull(), Q_FUNC_INFO, "invalid uuid");
1014 Q_ASSERT_X(peripheral, Q_FUNC_INFO, "invalid peripheral (nil)");
1015
1016 ObjCStrongReference<NSMutableArray> toVisit([NSMutableArray arrayWithArray:peripheral.services], RetainPolicy::doInitialRetain);
1017 ObjCStrongReference<NSMutableArray> toVisitNext([[NSMutableArray alloc] init], RetainPolicy::noInitialRetain);
1018 ObjCStrongReference<NSMutableSet> visitedNodes([[NSMutableSet alloc] init], RetainPolicy::noInitialRetain);
1019
1020 while (true) {
1021 for (NSUInteger i = 0, e = [toVisit count]; i < e; ++i) {
1022 CBService *const s = [toVisit objectAtIndex:i];
1023 if (equal_uuids(s.UUID, qtUuid))
1024 return s;
1025 if (![visitedNodes containsObject:s] && s.includedServices && s.includedServices.count) {
1026 [visitedNodes addObject:s];
1027 [toVisitNext addObjectsFromArray:s.includedServices];
1028 }
1029 }
1030
1031 if (![toVisitNext count])
1032 return nil;
1033
1034 toVisit.swap(toVisitNext);
1035 toVisitNext.reset([[NSMutableArray alloc] init], RetainPolicy::noInitialRetain);
1036 }
1037
1038 return nil;
1039}
1040
1041- (CBCharacteristic *)nextCharacteristicForService:(CBService*)service
1042 startingFrom:(CBCharacteristic *)characteristic
1043{
1044 Q_ASSERT_X(service, Q_FUNC_INFO, "invalid service (nil)");
1045 Q_ASSERT_X(characteristic, Q_FUNC_INFO, "invalid characteristic (nil)");
1046 Q_ASSERT_X(service.characteristics, Q_FUNC_INFO, "invalid service");
1047 Q_ASSERT_X(service.characteristics.count, Q_FUNC_INFO, "invalid service");
1048
1050
1051 // TODO: test that we NEVER have the same characteristic twice in array!
1052 // At the moment I just protect against this by iterating in a reverse
1053 // order (at least avoiding a potential inifite loop with '-indexOfObject:').
1054 NSArray *const cs = service.characteristics;
1055 if (cs.count == 1)
1056 return nil;
1057
1058 for (NSUInteger index = cs.count - 1; index != 0; --index) {
1059 if ([cs objectAtIndex:index] == characteristic) {
1060 if (index + 1 == cs.count)
1061 return nil;
1062 else
1063 return [cs objectAtIndex:index + 1];
1064 }
1065 }
1066
1067 Q_ASSERT_X([cs objectAtIndex:0] == characteristic, Q_FUNC_INFO,
1068 "characteristic was not found in service.characteristics");
1069
1070 return [cs objectAtIndex:1];
1071}
1072
1073- (CBCharacteristic *)nextCharacteristicForService:(CBService*)service
1074 startingFrom:(CBCharacteristic *)characteristic
1075 properties:(CBCharacteristicProperties)properties
1076{
1077 Q_ASSERT_X(service, Q_FUNC_INFO, "invalid service (nil)");
1078 Q_ASSERT_X(characteristic, Q_FUNC_INFO, "invalid characteristic (nil)");
1079 Q_ASSERT_X(service.characteristics, Q_FUNC_INFO, "invalid service");
1080 Q_ASSERT_X(service.characteristics.count, Q_FUNC_INFO, "invalid service");
1081
1083
1084 // TODO: test that we NEVER have the same characteristic twice in array!
1085 // At the moment I just protect against this by iterating in a reverse
1086 // order (at least avoiding a potential inifite loop with '-indexOfObject:').
1087 NSArray *const cs = service.characteristics;
1088 if (cs.count == 1)
1089 return nil;
1090
1091 NSUInteger index = cs.count - 1;
1092 for (; index != 0; --index) {
1093 if ([cs objectAtIndex:index] == characteristic) {
1094 if (index + 1 == cs.count) {
1095 return nil;
1096 } else {
1097 index += 1;
1098 break;
1099 }
1100 }
1101 }
1102
1103 if (!index) {
1104 Q_ASSERT_X([cs objectAtIndex:0] == characteristic, Q_FUNC_INFO,
1105 "characteristic not found in service.characteristics");
1106 index = 1;
1107 }
1108
1109 for (const NSUInteger e = cs.count; index < e; ++index) {
1110 CBCharacteristic *const c = [cs objectAtIndex:index];
1111 if (c.properties & properties)
1112 return c;
1113 }
1114
1115 return nil;
1116}
1117
1118- (CBDescriptor *)nextDescriptorForCharacteristic:(CBCharacteristic *)characteristic
1119 startingFrom:(CBDescriptor *)descriptor
1120{
1121 Q_ASSERT_X(characteristic, Q_FUNC_INFO, "invalid characteristic (nil)");
1122 Q_ASSERT_X(descriptor, Q_FUNC_INFO, "invalid descriptor (nil)");
1123 Q_ASSERT_X(characteristic.descriptors, Q_FUNC_INFO, "invalid characteristic");
1124 Q_ASSERT_X(characteristic.descriptors.count, Q_FUNC_INFO, "invalid characteristic");
1125
1127
1128 NSArray *const ds = characteristic.descriptors;
1129 if (ds.count == 1)
1130 return nil;
1131
1132 for (NSUInteger index = ds.count - 1; index != 0; --index) {
1133 if ([ds objectAtIndex:index] == descriptor) {
1134 if (index + 1 == ds.count)
1135 return nil;
1136 else
1137 return [ds objectAtIndex:index + 1];
1138 }
1139 }
1140
1141 Q_ASSERT_X([ds objectAtIndex:0] == descriptor, Q_FUNC_INFO,
1142 "descriptor was not found in characteristic.descriptors");
1143
1144 return [ds objectAtIndex:1];
1145}
1146
1147- (CBDescriptor *)descriptor:(const QBluetoothUuid &)qtUuid
1148 forCharacteristic:(CBCharacteristic *)ch
1149{
1150 if (qtUuid.isNull() || !ch)
1151 return nil;
1152
1154
1155 CBDescriptor *descriptor = nil;
1156 NSArray *const ds = ch.descriptors;
1157 if (ds && ds.count) {
1158 for (CBDescriptor *d in ds) {
1159 if (DarwinBluetooth::equal_uuids(d.UUID, qtUuid)) {
1160 descriptor = d;
1161 break;
1162 }
1163 }
1164 }
1165
1166 return descriptor;
1167}
1168
1169- (bool)cacheWriteValue:(const QByteArray &)value for:(NSObject *)obj
1170{
1171 Q_ASSERT_X(obj, Q_FUNC_INFO, "invalid object (nil)");
1172
1173 if ([obj isKindOfClass:[CBCharacteristic class]]) {
1174 CBCharacteristic *const ch = static_cast<CBCharacteristic *>(obj);
1175 if (!charMap.key(ch)) {
1176 qCWarning(QT_BT_DARWIN) << "unexpected characteristic, no handle found";
1177 return false;
1178 }
1179 } else if ([obj isKindOfClass:[CBDescriptor class]]) {
1180 CBDescriptor *const d = static_cast<CBDescriptor *>(obj);
1181 if (!descMap.key(d)) {
1182 qCWarning(QT_BT_DARWIN) << "unexpected descriptor, no handle found";
1183 return false;
1184 }
1185 } else {
1186 qCWarning(QT_BT_DARWIN) << "invalid object, characteristic "
1187 "or descriptor required";
1188 return false;
1189 }
1190
1191 if (valuesToWrite.contains(obj)) {
1192 // It can be a result of some previous errors - for example,
1193 // we never got a callback from a previous write.
1194 qCWarning(QT_BT_DARWIN) << "already has a cached value for this "
1195 "object, the value will be replaced";
1196 }
1197
1198 valuesToWrite[obj] = value;
1199 return true;
1200}
1201
1202- (void)reset
1203{
1204 requestPending = false;
1205 valuesToWrite.clear();
1206 requests.clear();
1207 servicesToDiscoverDetails.clear();
1208 lastValidHandle = 0;
1209 serviceMap.clear();
1210 charMap.clear();
1211 descMap.clear();
1212 currentReadHandle = 0;
1213 [self stopWatchers];
1214 // TODO: also serviceToVisit/VisitNext and visitedServices ?
1215}
1216
1217- (void)releasePeripheral
1218{
1219 [peripheral setDelegate:nil];
1220 [peripheral release];
1221 peripheral = nil;
1222}
1223
1224- (void)handleReadWriteError:(NSError *)error
1225{
1226 Q_ASSERT(notifier);
1227
1228 switch (error.code) {
1229 case 0x05: // GATT_INSUFFICIENT_AUTHORIZATION
1230 case 0x0F: // GATT_INSUFFICIENT_ENCRYPTION
1231 emit notifier->CBManagerError(QLowEnergyController::AuthorizationError);
1232 [self detach];
1233 break;
1234 default:
1235 break;
1236 }
1237}
1238
1239// CBCentralManagerDelegate (the real one).
1240
1241- (void)centralManagerDidUpdateState:(CBCentralManager *)central
1242{
1243 using namespace DarwinBluetooth;
1244
1245#pragma clang diagnostic push
1246#pragma clang diagnostic ignored "-Wunguarded-availability-new"
1247
1248 const auto state = central.state;
1249 if (state == CBManagerStateUnknown || state == CBManagerStateResetting) {
1250 // We still have to wait, docs say:
1251 // "The current state of the central manager is unknown;
1252 // an update is imminent." or
1253 // "The connection with the system service was momentarily
1254 // lost; an update is imminent."
1255 return;
1256 }
1257
1258 // Let's check some states we do not like first:
1259 if (state == CBManagerStateUnsupported || state == CBManagerStateUnauthorized) {
1260 managerState = CentralManagerIdle;
1261 // The LE is not supported or its usage was not authorized
1262 if (notifier) {
1263 if (state == CBManagerStateUnsupported)
1264 emit notifier->LEnotSupported();
1265 else
1266 emit notifier->CBManagerError(QLowEnergyController::MissingPermissionsError);
1267 }
1268 [self stopWatchers];
1269 return;
1270 }
1271
1272 if (state == CBManagerStatePoweredOff) {
1273 if (managerState == CentralManagerUpdating) {
1274 managerState = CentralManagerIdle;
1275 // I've seen this instead of Unsupported on OS X.
1276 if (notifier)
1277 emit notifier->LEnotSupported();
1278 } else {
1279#if !defined(Q_OS_MACOS)
1280 // The adapter was switched off. On iOS, Core Bluetooth drops the
1281 // connection without calling -centralManager:didDisconnectPeripheral:error:,
1282 // and the services, characteristics and descriptors cached in our
1283 // maps are no longer valid (we do not retain them). Forget them,
1284 // and the peripheral too: it has to be retrieved again once the
1285 // state is back to PoweredOn and a new connection is requested.
1286 [self reset];
1287 [self releasePeripheral];
1288 disconnectPending = false;
1289#endif // !Q_OS_MACOS
1290 managerState = CentralManagerIdle;
1291 // The controller reports this as a disconnect, if it was connected.
1292 if (notifier)
1293 emit notifier->CBManagerError(QLowEnergyController::InvalidBluetoothAdapterError);
1294 }
1295 [self stopWatchers];
1296 return;
1297 }
1298
1299 if (state == CBManagerStatePoweredOn) {
1300 if (managerState == CentralManagerUpdating && !disconnectPending) {
1301 managerState = CentralManagerIdle;
1302 [self retrievePeripheralAndConnect];
1303 }
1304 } else {
1305 // We actually handled all known states, but .. Core Bluetooth can change?
1306 Q_ASSERT_X(0, Q_FUNC_INFO, "invalid central's state");
1307 }
1308
1309#pragma clang diagnostic pop
1310}
1311
1312- (void)centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral *)aPeripheral
1313{
1314 Q_UNUSED(central);
1315 Q_UNUSED(aPeripheral);
1316
1317 if (managerState != DarwinBluetooth::CentralManagerConnecting) {
1318 // We called cancel but before disconnected, managed to connect?
1319 return;
1320 }
1321
1322 void([self mtu]);
1323
1324 [peripheral setDelegate:self];
1325
1326 managerState = DarwinBluetooth::CentralManagerIdle;
1327 if (notifier)
1328 emit notifier->connected();
1329}
1330
1331- (void)centralManager:(CBCentralManager *)central didFailToConnectPeripheral:(CBPeripheral *)aPeripheral
1332 error:(NSError *)error
1333{
1334 Q_UNUSED(central);
1335 Q_UNUSED(aPeripheral);
1336 Q_UNUSED(error);
1337
1338 if (managerState != DarwinBluetooth::CentralManagerConnecting) {
1339 // Canceled already.
1340 return;
1341 }
1342
1343 managerState = DarwinBluetooth::CentralManagerIdle;
1344 // TODO: better error mapping is required.
1345 if (notifier)
1346 notifier->CBManagerError(QLowEnergyController::UnknownRemoteDeviceError);
1347}
1348
1349- (void)centralManager:(CBCentralManager *)central didDisconnectPeripheral:(CBPeripheral *)aPeripheral
1350 error:(NSError *)error
1351{
1352 Q_UNUSED(central);
1353
1354 if (!peripheral || aPeripheral != peripheral) {
1355 // Either the adapter was switched off and this was handled
1356 // already in -centralManagerDidUpdateState:, or it's not our
1357 // peripheral.
1358 return;
1359 }
1360
1361 // Clear internal caches/data.
1362 [self reset];
1363
1364 if (error && managerState == DarwinBluetooth::CentralManagerDisconnecting) {
1365 managerState = DarwinBluetooth::CentralManagerIdle;
1366 qCWarning(QT_BT_DARWIN) << "failed to disconnect";
1367 if (notifier)
1368 emit notifier->CBManagerError(QLowEnergyController::UnknownRemoteDeviceError);
1369 } else {
1370 managerState = DarwinBluetooth::CentralManagerIdle;
1371 if (notifier)
1372 emit notifier->disconnected();
1373 }
1374}
1375
1376// CBPeripheralDelegate.
1377
1378- (void)peripheral:(CBPeripheral *)aPeripheral didDiscoverServices:(NSError *)error
1379{
1380 Q_UNUSED(aPeripheral);
1381
1382 using namespace DarwinBluetooth;
1383
1384 if (managerState != CentralManagerDiscovering) {
1385 // Canceled by -disconnectFromDevice, or as a result of a timeout.
1386 return;
1387 }
1388
1389 if (![self objectIsUnderWatch:aPeripheral operation:OperationTimeout::serviceDiscovery]) // Timed out already
1390 return;
1391
1393
1394 [self stopWatchingAfter:aPeripheral operation:OperationTimeout::serviceDiscovery];
1395
1396 managerState = CentralManagerIdle;
1397
1398 if (error) {
1399 NSLog(@"%s failed with error %@", Q_FUNC_INFO, error);
1400 // TODO: better error mapping required.
1401 // Emit an error which also causes the service discovery finished() signal
1402 if (notifier)
1403 emit notifier->CBManagerError(QLowEnergyController::UnknownError);
1404 return;
1405 }
1406
1407 [self discoverIncludedServices];
1408}
1409
1410- (void)peripheral:(CBPeripheral *)aPeripheral
1411 didModifyServices:(NSArray<CBService *> *)invalidatedServices
1412{
1413 Q_UNUSED(aPeripheral);
1414 Q_UNUSED(invalidatedServices);
1415
1416 qCWarning(QT_BT_DARWIN) << "The peripheral has modified its services.";
1417 // "This method is invoked whenever one or more services of a peripheral have changed.
1418 // A peripheral’s services have changed if:
1419 // * A service is removed from the peripheral’s database
1420 // * A new service is added to the peripheral’s database
1421 // * A service that was previously removed from the peripheral’s
1422 // database is readded to the database at a different location"
1423
1424 // In case new services were added - we have to discover them.
1425 // In case some were removed - we can end up with dangling pointers
1426 // (see our 'watchdogs', for example). To handle the situation
1427 // we stop all current operations here, report to QLowEnergyController
1428 // so that it can trigger re-discovery.
1429 [self reset];
1430 managerState = DarwinBluetooth::CentralManagerIdle;
1431 if (notifier)
1432 emit notifier->servicesWereModified();
1433}
1434
1435- (void)peripheral:(CBPeripheral *)aPeripheral didDiscoverIncludedServicesForService:(CBService *)service
1436 error:(NSError *)error
1437{
1438 Q_UNUSED(aPeripheral);
1439
1440 using namespace DarwinBluetooth;
1441
1442 if (managerState != CentralManagerDiscovering) {
1443 // Canceled by disconnectFromDevice or -peripheralDidDisconnect...
1444 return;
1445 }
1446
1447 if (![self objectIsUnderWatch:service operation:OperationTimeout::includedServicesDiscovery])
1448 return;
1449
1451
1452 Q_ASSERT_X(peripheral, Q_FUNC_INFO, "invalid peripheral (nil)");
1453
1454 [self stopWatchingAfter:service operation:OperationTimeout::includedServicesDiscovery];
1455 managerState = CentralManagerIdle;
1456
1457 if (error) {
1458 NSLog(@"%s: finished with error %@ for service %@",
1459 Q_FUNC_INFO, error, service.UUID);
1460 } else if (service.includedServices && service.includedServices.count) {
1461 // Now we have even more services to do included services discovery ...
1462 if (!servicesToVisitNext)
1463 servicesToVisitNext.reset([NSMutableArray arrayWithArray:service.includedServices], RetainPolicy::doInitialRetain);
1464 else
1465 [servicesToVisitNext addObjectsFromArray:service.includedServices];
1466 }
1467
1468 // Do we have something else to discover on this 'level'?
1469 ++currentService;
1470
1471 for (const NSUInteger e = [servicesToVisit count]; currentService < e; ++currentService) {
1472 CBService *const s = [servicesToVisit objectAtIndex:currentService];
1473 if (![visitedServices containsObject:s]) {
1474 // Continue with discovery ...
1475 [visitedServices addObject:s];
1476 managerState = CentralManagerDiscovering;
1477 [self watchAfter:s timeout:OperationTimeout::includedServicesDiscovery];
1478 return [peripheral discoverIncludedServices:nil forService:s];
1479 }
1480 }
1481
1482 // No services to visit more on this 'level'.
1483
1484 if (servicesToVisitNext && [servicesToVisitNext count]) {
1485 servicesToVisit.swap(servicesToVisitNext);
1486 servicesToVisitNext.reset();
1487
1488 currentService = 0;
1489 for (const NSUInteger e = [servicesToVisit count]; currentService < e; ++currentService) {
1490 CBService *const s = [servicesToVisit objectAtIndex:currentService];
1491 if (![visitedServices containsObject:s]) {
1492 [visitedServices addObject:s];
1493 managerState = CentralManagerDiscovering;
1494 [self watchAfter:s timeout:OperationTimeout::includedServicesDiscovery];
1495 return [peripheral discoverIncludedServices:nil forService:s];
1496 }
1497 }
1498 }
1499
1500 // Finally, if we're here, the service discovery is done!
1501
1502 // Release all these things now, no need to prolong their lifetime.
1503 visitedServices.reset();
1504 servicesToVisit.reset();
1505 servicesToVisitNext.reset();
1506
1507 if (notifier)
1508 emit notifier->serviceDiscoveryFinished();
1509}
1510
1511- (void)peripheral:(CBPeripheral *)aPeripheral didDiscoverCharacteristicsForService:(CBService *)service
1512 error:(NSError *)error
1513{
1514 // This method does not change 'managerState', we can have several
1515 // discoveries active.
1516 Q_UNUSED(aPeripheral);
1517
1518 if (!notifier) {
1519 // Detached.
1520 return;
1521 }
1522
1523 using namespace DarwinBluetooth;
1524
1525 if (![self objectIsUnderWatch:service operation:OperationTimeout::characteristicsDiscovery])
1526 return;
1527
1529
1530 [self stopWatchingAfter:service operation:OperationTimeout::characteristicsDiscovery];
1531
1532 const auto qtUuid = qt_uuid(service.UUID);
1533 const bool skipRead = servicesToDiscoverDetails[qtUuid] == DiscoveryMode::SkipValueDiscovery;
1534
1535 Q_ASSERT_X(managerState != CentralManagerUpdating, Q_FUNC_INFO, "invalid state");
1536
1537 if (error) {
1538 NSLog(@"%s failed with error: %@", Q_FUNC_INFO, error);
1539 // We did not discover any characteristics and can not discover descriptors,
1540 // inform our delegate (it will set a service state also).
1541 emit notifier->CBManagerError(qtUuid, QLowEnergyController::UnknownError);
1542 }
1543
1544 if (skipRead) {
1545 [self serviceDetailsDiscoveryFinished:service];
1546 return;
1547 }
1548 [self readCharacteristics:service];
1549}
1550
1551- (void)peripheral:(CBPeripheral *)aPeripheral
1552 didUpdateValueForCharacteristic:(CBCharacteristic *)characteristic
1553 error:(NSError *)error
1554{
1555 Q_UNUSED(aPeripheral);
1556
1557 if (!notifier) // Detached.
1558 return;
1559
1560 using namespace DarwinBluetooth;
1561
1563
1564 const bool readMatch = [self objectIsUnderWatch:characteristic operation:OperationTimeout::characteristicRead];
1565 if (readMatch)
1566 [self stopWatchingAfter:characteristic operation:OperationTimeout::characteristicRead];
1567
1568 Q_ASSERT_X(managerState != CentralManagerUpdating, Q_FUNC_INFO, "invalid state");
1569 Q_ASSERT_X(peripheral, Q_FUNC_INFO, "invalid peripheral (nil)");
1570
1571
1572 // First, let's check if we're discovering a service details now.
1573 CBService *const service = characteristic.service;
1574 const QBluetoothUuid qtUuid(qt_uuid(service.UUID));
1575 const bool isDetailsDiscovery = servicesToDiscoverDetails.contains(qtUuid);
1576 const QLowEnergyHandle chHandle = charMap.key(characteristic);
1577
1578 if (error) {
1579 NSLog(@"%s failed with error %@", Q_FUNC_INFO, error);
1580 if (!isDetailsDiscovery) {
1581 if (chHandle && chHandle == currentReadHandle) {
1582 currentReadHandle = 0;
1583 requestPending = false;
1584 emit notifier->CBManagerError(qtUuid, QLowEnergyService::CharacteristicReadError);
1585 [self handleReadWriteError:error];
1586 [self performNextRequest];
1587 }
1588 return;
1589 }
1590 }
1591
1592 if (isDetailsDiscovery) {
1593 if (readMatch) {
1594 // Test if we have any other characteristic to read yet.
1595 CBCharacteristic *const next = [self nextCharacteristicForService:characteristic.service
1596 startingFrom:characteristic properties:CBCharacteristicPropertyRead];
1597 if (next) {
1598 [self watchAfter:next timeout:OperationTimeout::characteristicRead];
1599 [peripheral readValueForCharacteristic:next];
1600 } else {
1601 [self discoverDescriptors:characteristic.service];
1602 }
1603 }
1604 } else {
1605 // This is (probably) the result of update notification.
1606 // It's very possible we can have an invalid handle here (0) -
1607 // if something esle is wrong (we subscribed for a notification),
1608 // disconnected (but other application is connected) and still receiveing
1609 // updated values ...
1610 // TODO: this must be properly tested.
1611 if (!chHandle) {
1612 qCCritical(QT_BT_DARWIN) << "unexpected update notification, "
1613 "no characteristic handle found";
1614 return;
1615 }
1616
1617 if (currentReadHandle == chHandle) {
1618 // Even if it was not a reply to our read request (no way to test it)
1619 // report it.
1620 requestPending = false;
1621 currentReadHandle = 0;
1622 //
1623 emit notifier->characteristicRead(chHandle, qt_bytearray(characteristic.value));
1624 [self performNextRequest];
1625 } else {
1626 emit notifier->characteristicUpdated(chHandle, qt_bytearray(characteristic.value));
1627 }
1628 }
1629}
1630
1631- (void)peripheral:(CBPeripheral *)aPeripheral
1632 didDiscoverDescriptorsForCharacteristic:(CBCharacteristic *)characteristic
1633 error:(NSError *)error
1634{
1635 // This method does not change 'managerState', we can
1636 // have several discoveries active at the same time.
1637 Q_UNUSED(aPeripheral);
1638
1639 if (!notifier) {
1640 // Detached, no need to continue ...
1641 return;
1642 }
1643
1645
1646 using namespace DarwinBluetooth;
1647
1648 if (![self objectIsUnderWatch:characteristic operation:OperationTimeout::descriptorsDiscovery])
1649 return;
1650
1651 [self stopWatchingAfter:characteristic operation:OperationTimeout::descriptorsDiscovery];
1652
1653 if (error) {
1654 NSLog(@"%s failed with error %@", Q_FUNC_INFO, error);
1655 // We can continue though ...
1656 }
1657
1658 // Do we have more characteristics on this service to discover descriptors?
1659 CBCharacteristic *const next = [self nextCharacteristicForService:characteristic.service
1660 startingFrom:characteristic];
1661 if (next) {
1662 [self watchAfter:next timeout:OperationTimeout::descriptorsDiscovery];
1663 [peripheral discoverDescriptorsForCharacteristic:next];
1664 } else {
1665 [self readDescriptors:characteristic.service];
1666 }
1667}
1668
1669- (void)peripheral:(CBPeripheral *)aPeripheral
1670 didUpdateValueForDescriptor:(CBDescriptor *)descriptor
1671 error:(NSError *)error
1672{
1673 Q_UNUSED(aPeripheral);
1674
1675 Q_ASSERT_X(peripheral, Q_FUNC_INFO, "invalid peripheral (nil)");
1676
1677 if (!notifier) {
1678 // Detached ...
1679 return;
1680 }
1681
1683
1684 using namespace DarwinBluetooth;
1685
1686 if (![self objectIsUnderWatch:descriptor operation:OperationTimeout::descriptorRead])
1687 return;
1688
1689 [self stopWatchingAfter:descriptor operation:OperationTimeout::descriptorRead];
1690
1691 CBService *const service = descriptor.characteristic.service;
1692 const QBluetoothUuid qtUuid(qt_uuid(service.UUID));
1693 const bool isDetailsDiscovery = servicesToDiscoverDetails.contains(qtUuid);
1694 const QLowEnergyHandle dHandle = descMap.key(descriptor);
1695
1696 if (error) {
1697 NSLog(@"%s failed with error %@", Q_FUNC_INFO, error);
1698
1699 if (!isDetailsDiscovery) {
1700 if (dHandle && dHandle == currentReadHandle) {
1701 currentReadHandle = 0;
1702 requestPending = false;
1703 emit notifier->CBManagerError(qtUuid, QLowEnergyService::DescriptorReadError);
1704 [self handleReadWriteError:error];
1705 [self performNextRequest];
1706 }
1707 return;
1708 }
1709 }
1710
1711 if (isDetailsDiscovery) {
1712 // Test if we have any other characteristic to read yet.
1713 CBDescriptor *const next = [self nextDescriptorForCharacteristic:descriptor.characteristic
1714 startingFrom:descriptor];
1715 if (next) {
1716 [self watchAfter:next timeout:OperationTimeout::descriptorRead];
1717 [peripheral readValueForDescriptor:next];
1718 } else {
1719 // We either have to read a value for a next descriptor
1720 // on a given characteristic, or continue with the
1721 // next characteristic in a given service (if any).
1722 CBCharacteristic *const ch = descriptor.characteristic;
1723 CBCharacteristic *nextCh = [self nextCharacteristicForService:ch.service
1724 startingFrom:ch];
1725 while (nextCh) {
1726 if (nextCh.descriptors && nextCh.descriptors.count) {
1727 CBDescriptor *desc = [nextCh.descriptors objectAtIndex:0];
1728 [self watchAfter:desc timeout:OperationTimeout::descriptorRead];
1729 return [peripheral readValueForDescriptor:desc];
1730 }
1731
1732 nextCh = [self nextCharacteristicForService:ch.service
1733 startingFrom:nextCh];
1734 }
1735
1736 [self serviceDetailsDiscoveryFinished:service];
1737 }
1738 } else {
1739 if (!dHandle) {
1740 qCCritical(QT_BT_DARWIN) << "unexpected value update notification, "
1741 "no descriptor handle found";
1742 return;
1743 }
1744
1745 if (dHandle == currentReadHandle) {
1746 currentReadHandle = 0;
1747 requestPending = false;
1748 emit notifier->descriptorRead(dHandle, qt_bytearray(static_cast<NSObject *>(descriptor.value)));
1749 [self performNextRequest];
1750 }
1751 }
1752}
1753
1754- (void)peripheral:(CBPeripheral *)aPeripheral
1755 didWriteValueForCharacteristic:(CBCharacteristic *)characteristic
1756 error:(NSError *)error
1757{
1758 Q_UNUSED(aPeripheral);
1759 Q_UNUSED(characteristic);
1760
1761 if (!notifier) {
1762 // Detached.
1763 return;
1764 }
1765
1766 // From docs:
1767 //
1768 // "This method is invoked only when your app calls the writeValue:forCharacteristic:type:
1769 // method with the CBCharacteristicWriteWithResponse constant specified as the write type.
1770 // If successful, the error parameter is nil. If unsuccessful,
1771 // the error parameter returns the cause of the failure."
1772
1773 using namespace DarwinBluetooth;
1774
1776
1777 if (![self objectIsUnderWatch:characteristic operation:OperationTimeout::characteristicWrite])
1778 return;
1779
1780 [self stopWatchingAfter:characteristic operation:OperationTimeout::characteristicWrite];
1781 requestPending = false;
1782
1783 // Error or not, but the cached value has to be deleted ...
1784 const QByteArray valueToReport(valuesToWrite.value(characteristic, QByteArray()));
1785 if (!valuesToWrite.remove(characteristic)) {
1786 qCWarning(QT_BT_DARWIN) << "no updated value found "
1787 "for characteristic";
1788 }
1789
1790 if (error) {
1791 NSLog(@"%s failed with error %@", Q_FUNC_INFO, error);
1792 emit notifier->CBManagerError(qt_uuid(characteristic.service.UUID),
1793 QLowEnergyService::CharacteristicWriteError);
1794 [self handleReadWriteError:error];
1795 } else {
1796 const QLowEnergyHandle cHandle = charMap.key(characteristic);
1797 emit notifier->characteristicWritten(cHandle, valueToReport);
1798 }
1799
1800 [self performNextRequest];
1801}
1802
1803- (void)peripheral:(CBPeripheral *)aPeripheral
1804 didWriteValueForDescriptor:(CBDescriptor *)descriptor
1805 error:(NSError *)error
1806{
1807 Q_UNUSED(aPeripheral);
1808
1809 if (!notifier) {
1810 // Detached already.
1811 return;
1812 }
1813
1814 using namespace DarwinBluetooth;
1815
1817
1818 requestPending = false;
1819
1820 // Error or not, a value (if any) must be removed.
1821 const QByteArray valueToReport(valuesToWrite.value(descriptor, QByteArray()));
1822 if (!valuesToWrite.remove(descriptor))
1823 qCWarning(QT_BT_DARWIN) << "no updated value found";
1824
1825 if (error) {
1826 NSLog(@"%s failed with error %@", Q_FUNC_INFO, error);
1827 emit notifier->CBManagerError(qt_uuid(descriptor.characteristic.service.UUID),
1828 QLowEnergyService::DescriptorWriteError);
1829 [self handleReadWriteError:error];
1830 } else {
1831 const QLowEnergyHandle dHandle = descMap.key(descriptor);
1832 Q_ASSERT_X(dHandle, Q_FUNC_INFO, "descriptor not found in the descriptors map");
1833 emit notifier->descriptorWritten(dHandle, valueToReport);
1834 }
1835
1836 [self performNextRequest];
1837}
1838
1839- (void)peripheral:(CBPeripheral *)aPeripheral
1840 didUpdateNotificationStateForCharacteristic:(CBCharacteristic *)characteristic
1841 error:(NSError *)error
1842{
1843 Q_UNUSED(aPeripheral);
1844
1845 if (!notifier)
1846 return;
1847
1848 using namespace DarwinBluetooth;
1849
1851
1852 requestPending = false;
1853
1854 const QBluetoothUuid qtUuid(QBluetoothUuid::DescriptorType::ClientCharacteristicConfiguration);
1855 CBDescriptor *const descriptor = [self descriptor:qtUuid forCharacteristic:characteristic];
1856 const QByteArray valueToReport(valuesToWrite.value(descriptor, QByteArray()));
1857 const int nRemoved = valuesToWrite.remove(descriptor);
1858
1859 if (error) {
1860 NSLog(@"%s failed with error %@", Q_FUNC_INFO, error);
1861 // In Qt's API it's a descriptor write actually.
1862 emit notifier->CBManagerError(qt_uuid(characteristic.service.UUID),
1863 QLowEnergyService::DescriptorWriteError);
1864 } else if (nRemoved) {
1865 const QLowEnergyHandle dHandle = descMap.key(descriptor);
1866 emit notifier->descriptorWritten(dHandle, valueToReport);
1867 }
1868
1869 [self performNextRequest];
1870}
1871
1872- (void)peripheral:(CBPeripheral *)aPeripheral didReadRSSI:(NSNumber *)RSSI error:(nullable NSError *)error
1873{
1874 Q_UNUSED(aPeripheral);
1875
1876 if (!notifier) // This controller was detached.
1877 return;
1878
1879 if (error) {
1880 NSLog(@"Reading RSSI finished with error: %@", error);
1881 return emit notifier->CBManagerError(QLowEnergyController::RssiReadError);
1882 }
1883
1884 if (!RSSI) {
1885 qCWarning(QT_BT_DARWIN, "Reading RSSI returned no value");
1886 return emit notifier->CBManagerError(QLowEnergyController::RssiReadError);
1887 }
1888
1889 emit notifier->rssiUpdated(qint16([RSSI shortValue]));
1890}
1891
1892- (void)detach
1893{
1894 if (notifier) {
1895 notifier->disconnect();
1896 notifier->deleteLater();
1897 notifier = nullptr;
1898 }
1899
1900 [self stopWatchers];
1901 [self disconnectFromDevice];
1902}
1903
1904@end
#define QT_BT_MAC_AUTORELEASEPOOL
Definition btutility_p.h:78
ObjCStrongReference< NSError > qt_timeoutNSError(OperationTimeout type)
auto qt_find_watchdog(const std::vector< GCDTimer > &watchdogs, id object, OperationTimeout type)
NSUInteger qt_countGATTEntries(CBService *service)