10#include <QtCore/qloggingcategory.h>
11#include <QtCore/qdebug.h>
12#include <QtCore/qmap.h>
18Q_DECLARE_METATYPE(QLowEnergyHandle)
31 Q_ASSERT_X(service, Q_FUNC_INFO,
"invalid service (nil)");
35 NSArray *
const cs = service.characteristics;
39 NSUInteger n = 1 + cs.count;
40 for (CBCharacteristic *c in cs) {
41 NSArray *
const ds = c.descriptors;
56 NSError *nsError = [[NSError alloc] initWithDomain:CBErrorDomain
57 code:CBErrorOperationCancelled
59 return ObjCStrongReference<NSError>(nsError, RetainPolicy::noInitialRetain);
64 return std::find_if(watchdogs.begin(), watchdogs.end(), [object, type](
const GCDTimer &other){
65 return [other objectUnderWatch] == object && [other timeoutType] == type;});
74@interface DarwinBTCentralManager (PrivateAPI)
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;
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;
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;
103- (
void)releasePeripheral;
107using DiscoveryMode = QLowEnergyService::DiscoveryMode;
109@implementation DarwinBTCentralManager
112 CBCentralManager *manager;
113 DarwinBluetooth::CentralManagerState managerState;
114 bool disconnectPending;
116 QBluetoothUuid deviceUuid;
118 DarwinBluetooth::LECBManagerNotifier *notifier;
122 DarwinBluetooth::ObjCStrongReference<NSMutableArray> servicesToVisit;
124 NSUInteger currentService;
126 DarwinBluetooth::ObjCStrongReference<NSMutableArray> servicesToVisitNext;
128 DarwinBluetooth::ObjCStrongReference<NSMutableSet> visitedServices;
130 QMap<QBluetoothUuid, DiscoveryMode> servicesToDiscoverDetails;
132 DarwinBluetooth::ServiceHash serviceMap;
133 DarwinBluetooth::CharHash charMap;
134 DarwinBluetooth::DescHash descMap;
136 QLowEnergyHandle lastValidHandle;
139 DarwinBluetooth::RequestQueue requests;
140 QLowEnergyHandle currentReadHandle;
142 DarwinBluetooth::ValueHash valuesToWrite;
145 std::vector<DarwinBluetooth::GCDTimer> timeoutWatchdogs;
147 CBPeripheral *peripheral;
151- (id)initWith:(DarwinBluetooth::LECBManagerNotifier *)aNotifier
153 using namespace DarwinBluetooth;
155 if (self = [super init]) {
157 managerState = CentralManagerIdle;
158 disconnectPending =
false;
160 notifier = aNotifier;
163 requestPending =
false;
164 currentReadHandle = 0;
166 if (Q_UNLIKELY(!qEnvironmentVariableIsEmpty(
"BLUETOOTH_GATT_TIMEOUT"))) {
168 const int value = qEnvironmentVariableIntValue(
"BLUETOOTH_GATT_TIMEOUT", &ok);
169 if (ok && value >= 0)
176 lastKnownMtu = defaultMtu;
189 visitedServices.reset();
190 servicesToVisit.reset();
191 servicesToVisitNext.reset();
193 [manager setDelegate:nil];
196 [peripheral setDelegate:nil];
197 [peripheral release];
200 notifier->deleteLater();
206- (CBPeripheral *)peripheral
211- (
void)watchAfter:(id)object timeout:(DarwinBluetooth::OperationTimeout)type
213 using namespace DarwinBluetooth;
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];
221- (
bool)objectIsUnderWatch:(id)object operation:(DarwinBluetooth::OperationTimeout)type
223 return DarwinBluetooth::qt_find_watchdog(timeoutWatchdogs, object, type) != timeoutWatchdogs.end();
226- (
void)stopWatchingAfter:(id)object operation:(DarwinBluetooth::OperationTimeout)type
228 auto pos = DarwinBluetooth::qt_find_watchdog(timeoutWatchdogs, object, type);
229 if (pos != timeoutWatchdogs.end()) {
231 timeoutWatchdogs.erase(pos);
237 for (
auto &watchdog : timeoutWatchdogs)
238 [watchdog cancelTimer];
239 timeoutWatchdogs.clear();
242- (
void)timeout:(id)sender
246 using namespace DarwinBluetooth;
248 DarwinBTGCDTimer *watcher =
static_cast<DarwinBTGCDTimer *>(sender);
249 id cbObject = [watcher objectUnderWatch];
250 const OperationTimeout type = [watcher timeoutType];
252 Q_ASSERT([self objectIsUnderWatch:cbObject operation:type]);
254 NSLog(@
"Timeout caused by: %@", cbObject);
258 const ObjCStrongReference<NSError> nsError(qt_timeoutNSError(type));
260 case OperationTimeout::serviceDiscovery:
261 qCWarning(QT_BT_DARWIN,
"Timeout in services discovery");
262 [self peripheral:peripheral didDiscoverServices:nsError];
264 case OperationTimeout::includedServicesDiscovery:
265 qCWarning(QT_BT_DARWIN,
"Timeout in included services discovery");
266 [self peripheral:peripheral didDiscoverIncludedServicesForService:cbObject error:nsError];
268 case OperationTimeout::characteristicsDiscovery:
269 qCWarning(QT_BT_DARWIN,
"Timeout in characteristics discovery");
270 [self peripheral:peripheral didDiscoverCharacteristicsForService:cbObject error:nsError];
272 case OperationTimeout::characteristicRead:
273 qCWarning(QT_BT_DARWIN,
"Timeout while reading a characteristic");
274 [self peripheral:peripheral didUpdateValueForCharacteristic:cbObject error:nsError];
276 case OperationTimeout::descriptorsDiscovery:
277 qCWarning(QT_BT_DARWIN,
"Timeout in descriptors discovery");
278 [self peripheral:peripheral didDiscoverDescriptorsForCharacteristic:cbObject error:nsError];
280 case OperationTimeout::descriptorRead:
281 qCWarning(QT_BT_DARWIN,
"Timeout while reading a descriptor");
282 [self peripheral:peripheral didUpdateValueForDescriptor:cbObject error:nsError];
284 case OperationTimeout::characteristicWrite:
285 qCWarning(QT_BT_DARWIN,
"Timeout while writing a characteristic with response");
286 [self peripheral:peripheral didWriteValueForCharacteristic:cbObject error:nsError];
291- (
void)connectToDevice:(
const QBluetoothUuid &)aDeviceUuid
293 disconnectPending =
false;
294 deviceUuid = aDeviceUuid;
299 if (
const dispatch_queue_t leQueue = DarwinBluetooth::qt_LE_queue()) {
300 managerState = DarwinBluetooth::CentralManagerUpdating;
301 manager = [[CBCentralManager alloc] initWithDelegate:self queue:leQueue];
305 managerState = DarwinBluetooth::CentralManagerIdle;
306 qCWarning(QT_BT_DARWIN) <<
"failed to allocate a central manager";
308 emit notifier->CBManagerError(QLowEnergyController::ConnectionError);
310 }
else if (managerState != DarwinBluetooth::CentralManagerUpdating) {
311 [self retrievePeripheralAndConnect];
315- (
void)retrievePeripheralAndConnect
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");
321 if ([self isConnected]) {
322 qCDebug(QT_BT_DARWIN) <<
"already connected";
324 emit notifier->connected();
326 }
else if (peripheral) {
329 [self connectToPeripheral];
333 using namespace DarwinBluetooth;
336 const ObjCScopedPointer<NSMutableArray> uuids([[NSMutableArray alloc] init], RetainPolicy::noInitialRetain);
338 qCWarning(QT_BT_DARWIN) <<
"failed to allocate identifiers";
340 emit notifier->CBManagerError(QLowEnergyController::ConnectionError);
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);
350 qCWarning(QT_BT_DARWIN) <<
"failed to allocate NSUUID identifier";
352 emit notifier->CBManagerError(QLowEnergyController::ConnectionError);
356 [uuids addObject:nsUuid];
359 NSArray *
const peripherals = [manager retrievePeripheralsWithIdentifiers:uuids];
360 if (!peripherals || peripherals.count != 1) {
361 qCWarning(QT_BT_DARWIN) <<
"failed to retrieve a peripheral";
363 emit notifier->CBManagerError(QLowEnergyController::UnknownRemoteDeviceError);
367 peripheral = [
static_cast<CBPeripheral *>([peripherals objectAtIndex:0]) retain];
368 [self connectToPeripheral];
371- (
void)connectToPeripheral
373 using namespace DarwinBluetooth;
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");
380 if ([self isConnected]) {
381 qCDebug(QT_BT_DARWIN) <<
"already connected";
383 emit notifier->connected();
385 [self setMtu:defaultMtu];
386 qCDebug(QT_BT_DARWIN) <<
"trying to connect";
387 managerState = CentralManagerConnecting;
388 [manager connectPeripheral:peripheral options:nil];
397 return peripheral.state == CBPeripheralStateConnected;
400- (
void)disconnectFromDevice
404 if (managerState == DarwinBluetooth::CentralManagerUpdating) {
405 disconnectPending =
true;
412 emit notifier->disconnected();
415 disconnectPending =
false;
416 if ([self isConnected])
417 managerState = DarwinBluetooth::CentralManagerDisconnecting;
419 managerState = DarwinBluetooth::CentralManagerIdle;
426 [manager cancelPeripheralConnection:peripheral];
430- (
void)discoverServices
432 using namespace DarwinBluetooth;
434 Q_ASSERT_X(peripheral, Q_FUNC_INFO,
"invalid peripheral (nil)");
435 Q_ASSERT_X(managerState == CentralManagerIdle, Q_FUNC_INFO,
"invalid state");
444 managerState = CentralManagerDiscovering;
445 [self watchAfter:peripheral timeout:OperationTimeout::serviceDiscovery];
446 [peripheral discoverServices:nil];
449- (
void)discoverIncludedServices
451 using namespace DarwinBluetooth;
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)");
459 NSArray *
const services = peripheral.services;
460 if (!services || !services.count) {
463 emit notifier->serviceDiscoveryFinished();
466 servicesToVisitNext.reset();
467 servicesToVisit.reset([NSMutableArray arrayWithArray:services], RetainPolicy::doInitialRetain);
469 visitedServices.reset([NSMutableSet setWithCapacity:peripheral.services.count], RetainPolicy::doInitialRetain);
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];
479- (
void)discoverServiceDetails:(
const QBluetoothUuid &)serviceUuid
480 readValues:(
bool) read
486 using namespace DarwinBluetooth;
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)");
492 if (servicesToDiscoverDetails.contains(serviceUuid)) {
493 qCWarning(QT_BT_DARWIN) <<
"already discovering for"
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];
508 qCWarning(QT_BT_DARWIN) <<
"unknown service uuid"
512 emit notifier->CBManagerError(serviceUuid, QLowEnergyService::UnknownError);
515- (
void)readCharacteristics:(CBService *)service
519 Q_ASSERT_X(service, Q_FUNC_INFO,
"invalid service (nil)");
521 using namespace DarwinBluetooth;
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)");
529 if (!service.characteristics || !service.characteristics.count)
530 return [self serviceDetailsDiscoveryFinished:service];
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];
541 [self discoverDescriptors:service];
544- (
void)discoverDescriptors:(CBService *)service
548 Q_ASSERT_X(service, Q_FUNC_INFO,
"invalid service (nil)");
550 using namespace DarwinBluetooth;
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)");
559 if (!service.characteristics || !service.characteristics.count) {
560 [self serviceDetailsDiscoveryFinished:service];
563 CBCharacteristic *ch = [service.characteristics objectAtIndex:0];
564 [self watchAfter:ch timeout:OperationTimeout::descriptorsDiscovery];
565 [peripheral discoverDescriptorsForCharacteristic:ch];
569- (
void)readDescriptors:(CBService *)service
571 using namespace DarwinBluetooth;
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)");
579 NSArray *
const cs = service.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];
591 [self serviceDetailsDiscoveryFinished:service];
594- (
void)serviceDetailsDiscoveryFinished:(CBService *)service
596 Q_ASSERT_X(service, Q_FUNC_INFO,
"invalid service (nil)");
598 using namespace DarwinBluetooth;
602 const QBluetoothUuid serviceUuid(qt_uuid(service.UUID));
603 const bool skipValues = servicesToDiscoverDetails[serviceUuid] == DiscoveryMode::SkipValueDiscovery;
604 servicesToDiscoverDetails.remove(serviceUuid);
606 const NSUInteger nHandles = qt_countGATTEntries(service);
607 Q_ASSERT_X(nHandles, Q_FUNC_INFO,
"unexpected number of GATT entires");
609 const QLowEnergyHandle maxHandle = std::numeric_limits<QLowEnergyHandle>::max();
610 if (nHandles >= maxHandle || lastValidHandle > maxHandle - nHandles) {
612 qCWarning(QT_BT_DARWIN) <<
"can not allocate more handles";
614 notifier->CBManagerError(serviceUuid, QLowEnergyService::OperationError);
621 QSharedPointer<QLowEnergyServicePrivate> qtService(
new QLowEnergyServicePrivate);
622 qtService->uuid = serviceUuid;
627 serviceMap[lastValidHandle] = service;
628 qtService->startHandle = lastValidHandle;
630 NSArray *
const cs = service.characteristics;
632 if (cs && cs.count) {
633 QHash<QLowEnergyHandle, QLowEnergyServicePrivate::CharData> charList;
635 for (CBCharacteristic *c in cs) {
638 charMap[lastValidHandle] = c;
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);
645 newChar.value = qt_bytearray(c.value);
646 newChar.valueHandle = lastValidHandle;
648 NSArray *
const ds = c.descriptors;
649 if (ds && ds.count) {
650 QHash<QLowEnergyHandle, QLowEnergyServicePrivate::DescData> descList;
651 for (CBDescriptor *d in ds) {
654 descMap[lastValidHandle] = d;
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;
661 if (newDesc.uuid == QBluetoothUuid::DescriptorType::ClientCharacteristicConfiguration) {
662 if (newDesc.value.size() && (newDesc.value[0] & 3))
663 [peripheral setNotifyValue:YES forCharacteristic:c];
667 newChar.descriptorList = descList;
670 charList[newChar.valueHandle] = newChar;
673 qtService->characteristicList = charList;
676 qtService->endHandle = lastValidHandle;
679 emit notifier->serviceDetailsDiscoveryFinished(qtService);
682- (
void)performNextRequest
684 using namespace DarwinBluetooth;
686 if (requestPending || !requests.size())
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];
703- (
void)performNextReadRequest
705 using namespace DarwinBluetooth;
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");
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];
722 requestPending =
true;
723 currentReadHandle = request.handle;
726 [peripheral readValueForCharacteristic:charMap[request.handle]];
728 if (!descMap.contains(request.handle)) {
729 qCWarning(QT_BT_DARWIN) <<
"descriptor with handle"
730 << request.handle <<
"not found";
731 return [self performNextRequest];
734 requestPending =
true;
735 currentReadHandle = request.handle;
737 [peripheral readValueForDescriptor:descMap[request.handle]];
741- (
void)performNextWriteRequest
743 using namespace DarwinBluetooth;
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");
753 const LERequest request(requests.dequeue());
755 if (request.type == LERequest::DescWrite) {
756 if (!descMap.contains(request.handle)) {
757 qCWarning(QT_BT_DARWIN) <<
"handle:" << request.handle
759 return [self performNextRequest];
762 CBDescriptor *
const descriptor = descMap[request.handle];
763 ObjCStrongReference<NSData> data(data_from_bytearray(request.value));
766 qCWarning(QT_BT_DARWIN) <<
"failed to allocate an NSData object";
767 return [self performNextRequest];
770 if (![self cacheWriteValue:request.value
for:descriptor])
771 return [self performNextRequest];
773 requestPending =
true;
774 return [peripheral writeValue:data.data() forDescriptor:descriptor];
776 if (!charMap.contains(request.handle)) {
777 qCWarning(QT_BT_DARWIN) <<
"characteristic with handle:"
778 << request.handle <<
"not found";
779 return [self performNextRequest];
782 CBCharacteristic *
const characteristic = charMap[request.handle];
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");
790 if (![self cacheWriteValue:request.value
for:descriptor])
791 return [self performNextRequest];
794 if (request.value.size())
795 enable = request.value[0] & 3;
797 requestPending =
true;
798 [peripheral setNotifyValue:enable forCharacteristic:characteristic];
800 ObjCStrongReference<NSData> data(data_from_bytearray(request.value));
803 qCWarning(QT_BT_DARWIN) <<
"failed to allocate NSData object";
804 return [self performNextRequest];
808 if (request.withResponse) {
809 if (![self cacheWriteValue:request.value
for:characteristic])
810 return [self performNextRequest];
812 requestPending =
true;
813 [self watchAfter:characteristic timeout:OperationTimeout::characteristicWrite];
814 [peripheral writeValue:data.data() forCharacteristic:characteristic
815 type:CBCharacteristicWriteWithResponse];
817 [peripheral writeValue:data.data() forCharacteristic:characteristic
818 type:CBCharacteristicWriteWithoutResponse];
819 [self performNextRequest];
825- (
void)setMtu:(
int)newMtu
827 if (lastKnownMtu == newMtu)
829 lastKnownMtu = newMtu;
831 emit notifier->mtuChanged(newMtu);
836 using namespace DarwinBluetooth;
838 if (![self isConnected]) {
839 [self setMtu:defaultMtu];
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];
849 [self setMtu:
int(maxLen) + 3];
856 Q_ASSERT([self isConnected]);
857 [peripheral readRSSI];
860- (
void)setNotifyValue:(
const QByteArray &)value
861 forCharacteristic:(QLowEnergyHandle)charHandle
862 onService:(
const QBluetoothUuid &)serviceUuid
864 using namespace DarwinBluetooth;
866 Q_ASSERT_X(charHandle, Q_FUNC_INFO,
"invalid characteristic handle (0)");
868 if (!charMap.contains(charHandle)) {
869 qCWarning(QT_BT_DARWIN) <<
"unknown characteristic handle"
872 emit notifier->CBManagerError(serviceUuid,
873 QLowEnergyService::DescriptorWriteError);
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";
885 emit notifier->CBManagerError(serviceUuid,
886 QLowEnergyService::DescriptorWriteError);
892 request.type = LERequest::ClientConfiguration;
893 request.handle = charHandle;
894 request.value = value;
896 requests.enqueue(request);
897 [self performNextRequest];
900- (
void)readCharacteristic:(QLowEnergyHandle)charHandle
901 onService:(
const QBluetoothUuid &)serviceUuid
903 using namespace DarwinBluetooth;
905 Q_ASSERT_X(charHandle, Q_FUNC_INFO,
"invalid characteristic handle (0)");
909 if (!charMap.contains(charHandle)) {
910 qCWarning(QT_BT_DARWIN) <<
"characteristic:" << charHandle <<
"not found";
912 emit notifier->CBManagerError(serviceUuid,
913 QLowEnergyService::CharacteristicReadError);
920 request.type = LERequest::CharRead;
921 request.handle = charHandle;
923 requests.enqueue(request);
924 [self performNextRequest];
927- (
void)write:(
const QByteArray &)value
928 charHandle:(QLowEnergyHandle)charHandle
929 onService:(
const QBluetoothUuid &)serviceUuid
930 withResponse:(
bool)withResponse
932 using namespace DarwinBluetooth;
934 Q_ASSERT_X(charHandle, Q_FUNC_INFO,
"invalid characteristic handle (0)");
938 if (!charMap.contains(charHandle)) {
939 qCWarning(QT_BT_DARWIN) <<
"characteristic:" << charHandle <<
"not found";
941 emit notifier->CBManagerError(serviceUuid,
942 QLowEnergyService::CharacteristicWriteError);
948 request.type = LERequest::CharWrite;
949 request.withResponse = withResponse;
950 request.handle = charHandle;
951 request.value = value;
953 requests.enqueue(request);
954 [self performNextRequest];
957- (
void)readDescriptor:(QLowEnergyHandle)descHandle
958 onService:(
const QBluetoothUuid &)serviceUuid
960 using namespace DarwinBluetooth;
962 Q_ASSERT_X(descHandle, Q_FUNC_INFO,
"invalid descriptor handle (0)");
964 if (!descMap.contains(descHandle)) {
965 qCWarning(QT_BT_DARWIN) <<
"handle:" << descHandle <<
"not found";
967 emit notifier->CBManagerError(serviceUuid,
968 QLowEnergyService::DescriptorReadError);
974 request.type = LERequest::DescRead;
975 request.handle = descHandle;
977 requests.enqueue(request);
978 [self performNextRequest];
981- (
void)write:(
const QByteArray &)value
982 descHandle:(QLowEnergyHandle)descHandle
983 onService:(
const QBluetoothUuid &)serviceUuid
985 using namespace DarwinBluetooth;
987 Q_ASSERT_X(descHandle, Q_FUNC_INFO,
"invalid descriptor handle (0)");
989 if (!descMap.contains(descHandle)) {
990 qCWarning(QT_BT_DARWIN) <<
"handle:" << descHandle <<
"not found";
992 emit notifier->CBManagerError(serviceUuid,
993 QLowEnergyService::DescriptorWriteError);
999 request.type = LERequest::DescWrite;
1000 request.handle = descHandle;
1001 request.value = value;
1003 requests.enqueue(request);
1004 [self performNextRequest];
1009- (CBService *)serviceForUUID:(
const QBluetoothUuid &)qtUuid
1011 using namespace DarwinBluetooth;
1013 Q_ASSERT_X(!qtUuid.isNull(), Q_FUNC_INFO,
"invalid uuid");
1014 Q_ASSERT_X(peripheral, Q_FUNC_INFO,
"invalid peripheral (nil)");
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);
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))
1025 if (![visitedNodes containsObject:s] && s.includedServices && s.includedServices.count) {
1026 [visitedNodes addObject:s];
1027 [toVisitNext addObjectsFromArray:s.includedServices];
1031 if (![toVisitNext count])
1034 toVisit.swap(toVisitNext);
1035 toVisitNext.reset([[NSMutableArray alloc] init], RetainPolicy::noInitialRetain);
1041- (CBCharacteristic *)nextCharacteristicForService:(CBService*)service
1042 startingFrom:(CBCharacteristic *)characteristic
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");
1054 NSArray *
const cs = service.characteristics;
1058 for (NSUInteger index = cs.count - 1; index != 0; --index) {
1059 if ([cs objectAtIndex:index] == characteristic) {
1060 if (index + 1 == cs.count)
1063 return [cs objectAtIndex:index + 1];
1067 Q_ASSERT_X([cs objectAtIndex:0] == characteristic, Q_FUNC_INFO,
1068 "characteristic was not found in service.characteristics");
1070 return [cs objectAtIndex:1];
1073- (CBCharacteristic *)nextCharacteristicForService:(CBService*)service
1074 startingFrom:(CBCharacteristic *)characteristic
1075 properties:(CBCharacteristicProperties)properties
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");
1087 NSArray *
const cs = service.characteristics;
1091 NSUInteger index = cs.count - 1;
1092 for (; index != 0; --index) {
1093 if ([cs objectAtIndex:index] == characteristic) {
1094 if (index + 1 == cs.count) {
1104 Q_ASSERT_X([cs objectAtIndex:0] == characteristic, Q_FUNC_INFO,
1105 "characteristic not found in service.characteristics");
1109 for (
const NSUInteger e = cs.count; index < e; ++index) {
1110 CBCharacteristic *
const c = [cs objectAtIndex:index];
1111 if (c.properties & properties)
1118- (CBDescriptor *)nextDescriptorForCharacteristic:(CBCharacteristic *)characteristic
1119 startingFrom:(CBDescriptor *)descriptor
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");
1128 NSArray *
const ds = characteristic.descriptors;
1132 for (NSUInteger index = ds.count - 1; index != 0; --index) {
1133 if ([ds objectAtIndex:index] == descriptor) {
1134 if (index + 1 == ds.count)
1137 return [ds objectAtIndex:index + 1];
1141 Q_ASSERT_X([ds objectAtIndex:0] == descriptor, Q_FUNC_INFO,
1142 "descriptor was not found in characteristic.descriptors");
1144 return [ds objectAtIndex:1];
1147- (CBDescriptor *)descriptor:(
const QBluetoothUuid &)qtUuid
1148 forCharacteristic:(CBCharacteristic *)ch
1150 if (qtUuid.isNull() || !ch)
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)) {
1169- (
bool)cacheWriteValue:(
const QByteArray &)value
for:(NSObject *)obj
1171 Q_ASSERT_X(obj, Q_FUNC_INFO,
"invalid object (nil)");
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";
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";
1186 qCWarning(QT_BT_DARWIN) <<
"invalid object, characteristic "
1187 "or descriptor required";
1191 if (valuesToWrite.contains(obj)) {
1194 qCWarning(QT_BT_DARWIN) <<
"already has a cached value for this "
1195 "object, the value will be replaced";
1198 valuesToWrite[obj] = value;
1204 requestPending =
false;
1205 valuesToWrite.clear();
1207 servicesToDiscoverDetails.clear();
1208 lastValidHandle = 0;
1212 currentReadHandle = 0;
1213 [self stopWatchers];
1217- (
void)releasePeripheral
1219 [peripheral setDelegate:nil];
1220 [peripheral release];
1224- (
void)handleReadWriteError:(NSError *)error
1228 switch (error.code) {
1231 emit notifier->CBManagerError(QLowEnergyController::AuthorizationError);
1241- (
void)centralManagerDidUpdateState:(CBCentralManager *)central
1243 using namespace DarwinBluetooth;
1245#pragma clang diagnostic push
1246#pragma clang diagnostic ignored "-Wunguarded-availability-new"
1248 const auto state = central.state;
1249 if (state == CBManagerStateUnknown || state == CBManagerStateResetting) {
1259 if (state == CBManagerStateUnsupported || state == CBManagerStateUnauthorized) {
1260 managerState = CentralManagerIdle;
1263 if (state == CBManagerStateUnsupported)
1264 emit notifier->LEnotSupported();
1266 emit notifier->CBManagerError(QLowEnergyController::MissingPermissionsError);
1268 [self stopWatchers];
1272 if (state == CBManagerStatePoweredOff) {
1273 if (managerState == CentralManagerUpdating) {
1274 managerState = CentralManagerIdle;
1277 emit notifier->LEnotSupported();
1279#if !defined(Q_OS_MACOS)
1287 [self releasePeripheral];
1288 disconnectPending =
false;
1290 managerState = CentralManagerIdle;
1293 emit notifier->CBManagerError(QLowEnergyController::InvalidBluetoothAdapterError);
1295 [self stopWatchers];
1299 if (state == CBManagerStatePoweredOn) {
1300 if (managerState == CentralManagerUpdating && !disconnectPending) {
1301 managerState = CentralManagerIdle;
1302 [self retrievePeripheralAndConnect];
1306 Q_ASSERT_X(0, Q_FUNC_INFO,
"invalid central's state");
1309#pragma clang diagnostic pop
1312- (
void)centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral *)aPeripheral
1315 Q_UNUSED(aPeripheral);
1317 if (managerState != DarwinBluetooth::CentralManagerConnecting) {
1324 [peripheral setDelegate:self];
1326 managerState = DarwinBluetooth::CentralManagerIdle;
1328 emit notifier->connected();
1331- (
void)centralManager:(CBCentralManager *)central didFailToConnectPeripheral:(CBPeripheral *)aPeripheral
1332 error:(NSError *)error
1335 Q_UNUSED(aPeripheral);
1338 if (managerState != DarwinBluetooth::CentralManagerConnecting) {
1343 managerState = DarwinBluetooth::CentralManagerIdle;
1346 notifier->CBManagerError(QLowEnergyController::UnknownRemoteDeviceError);
1349- (
void)centralManager:(CBCentralManager *)central didDisconnectPeripheral:(CBPeripheral *)aPeripheral
1350 error:(NSError *)error
1354 if (!peripheral || aPeripheral != peripheral) {
1364 if (error && managerState == DarwinBluetooth::CentralManagerDisconnecting) {
1365 managerState = DarwinBluetooth::CentralManagerIdle;
1366 qCWarning(QT_BT_DARWIN) <<
"failed to disconnect";
1368 emit notifier->CBManagerError(QLowEnergyController::UnknownRemoteDeviceError);
1370 managerState = DarwinBluetooth::CentralManagerIdle;
1372 emit notifier->disconnected();
1378- (
void)peripheral:(CBPeripheral *)aPeripheral didDiscoverServices:(NSError *)error
1380 Q_UNUSED(aPeripheral);
1382 using namespace DarwinBluetooth;
1384 if (managerState != CentralManagerDiscovering) {
1389 if (![self objectIsUnderWatch:aPeripheral operation:OperationTimeout::serviceDiscovery])
1394 [self stopWatchingAfter:aPeripheral operation:OperationTimeout::serviceDiscovery];
1396 managerState = CentralManagerIdle;
1399 NSLog(@
"%s failed with error %@", Q_FUNC_INFO, error);
1403 emit notifier->CBManagerError(QLowEnergyController::UnknownError);
1407 [self discoverIncludedServices];
1410- (
void)peripheral:(CBPeripheral *)aPeripheral
1411 didModifyServices:(NSArray<CBService *> *)invalidatedServices
1413 Q_UNUSED(aPeripheral);
1414 Q_UNUSED(invalidatedServices);
1416 qCWarning(QT_BT_DARWIN) <<
"The peripheral has modified its services.";
1430 managerState = DarwinBluetooth::CentralManagerIdle;
1432 emit notifier->servicesWereModified();
1435- (
void)peripheral:(CBPeripheral *)aPeripheral didDiscoverIncludedServicesForService:(CBService *)service
1436 error:(NSError *)error
1438 Q_UNUSED(aPeripheral);
1440 using namespace DarwinBluetooth;
1442 if (managerState != CentralManagerDiscovering) {
1447 if (![self objectIsUnderWatch:service operation:OperationTimeout::includedServicesDiscovery])
1452 Q_ASSERT_X(peripheral, Q_FUNC_INFO,
"invalid peripheral (nil)");
1454 [self stopWatchingAfter:service operation:OperationTimeout::includedServicesDiscovery];
1455 managerState = CentralManagerIdle;
1458 NSLog(@
"%s: finished with error %@ for service %@",
1459 Q_FUNC_INFO, error, service.UUID);
1460 }
else if (service.includedServices && service.includedServices.count) {
1462 if (!servicesToVisitNext)
1463 servicesToVisitNext.reset([NSMutableArray arrayWithArray:service.includedServices], RetainPolicy::doInitialRetain);
1465 [servicesToVisitNext addObjectsFromArray:service.includedServices];
1471 for (
const NSUInteger e = [servicesToVisit count]; currentService < e; ++currentService) {
1472 CBService *
const s = [servicesToVisit objectAtIndex:currentService];
1473 if (![visitedServices containsObject:s]) {
1475 [visitedServices addObject:s];
1476 managerState = CentralManagerDiscovering;
1477 [self watchAfter:s timeout:OperationTimeout::includedServicesDiscovery];
1478 return [peripheral discoverIncludedServices:nil forService:s];
1484 if (servicesToVisitNext && [servicesToVisitNext count]) {
1485 servicesToVisit.swap(servicesToVisitNext);
1486 servicesToVisitNext.reset();
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];
1503 visitedServices.reset();
1504 servicesToVisit.reset();
1505 servicesToVisitNext.reset();
1508 emit notifier->serviceDiscoveryFinished();
1511- (
void)peripheral:(CBPeripheral *)aPeripheral didDiscoverCharacteristicsForService:(CBService *)service
1512 error:(NSError *)error
1516 Q_UNUSED(aPeripheral);
1523 using namespace DarwinBluetooth;
1525 if (![self objectIsUnderWatch:service operation:OperationTimeout::characteristicsDiscovery])
1530 [self stopWatchingAfter:service operation:OperationTimeout::characteristicsDiscovery];
1532 const auto qtUuid = qt_uuid(service.UUID);
1533 const bool skipRead = servicesToDiscoverDetails[qtUuid] == DiscoveryMode::SkipValueDiscovery;
1535 Q_ASSERT_X(managerState != CentralManagerUpdating, Q_FUNC_INFO,
"invalid state");
1538 NSLog(@
"%s failed with error: %@", Q_FUNC_INFO, error);
1541 emit notifier->CBManagerError(qtUuid, QLowEnergyController::UnknownError);
1545 [self serviceDetailsDiscoveryFinished:service];
1548 [self readCharacteristics:service];
1551- (
void)peripheral:(CBPeripheral *)aPeripheral
1552 didUpdateValueForCharacteristic:(CBCharacteristic *)characteristic
1553 error:(NSError *)error
1555 Q_UNUSED(aPeripheral);
1560 using namespace DarwinBluetooth;
1564 const bool readMatch = [self objectIsUnderWatch:characteristic operation:OperationTimeout::characteristicRead];
1566 [self stopWatchingAfter:characteristic operation:OperationTimeout::characteristicRead];
1568 Q_ASSERT_X(managerState != CentralManagerUpdating, Q_FUNC_INFO,
"invalid state");
1569 Q_ASSERT_X(peripheral, Q_FUNC_INFO,
"invalid peripheral (nil)");
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);
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];
1592 if (isDetailsDiscovery) {
1595 CBCharacteristic *
const next = [self nextCharacteristicForService:characteristic.service
1596 startingFrom:characteristic properties:CBCharacteristicPropertyRead];
1598 [self watchAfter:next timeout:OperationTimeout::characteristicRead];
1599 [peripheral readValueForCharacteristic:next];
1601 [self discoverDescriptors:characteristic.service];
1612 qCCritical(QT_BT_DARWIN) <<
"unexpected update notification, "
1613 "no characteristic handle found";
1617 if (currentReadHandle == chHandle) {
1620 requestPending =
false;
1621 currentReadHandle = 0;
1623 emit notifier->characteristicRead(chHandle, qt_bytearray(characteristic.value));
1624 [self performNextRequest];
1626 emit notifier->characteristicUpdated(chHandle, qt_bytearray(characteristic.value));
1631- (
void)peripheral:(CBPeripheral *)aPeripheral
1632 didDiscoverDescriptorsForCharacteristic:(CBCharacteristic *)characteristic
1633 error:(NSError *)error
1637 Q_UNUSED(aPeripheral);
1646 using namespace DarwinBluetooth;
1648 if (![self objectIsUnderWatch:characteristic operation:OperationTimeout::descriptorsDiscovery])
1651 [self stopWatchingAfter:characteristic operation:OperationTimeout::descriptorsDiscovery];
1654 NSLog(@
"%s failed with error %@", Q_FUNC_INFO, error);
1659 CBCharacteristic *
const next = [self nextCharacteristicForService:characteristic.service
1660 startingFrom:characteristic];
1662 [self watchAfter:next timeout:OperationTimeout::descriptorsDiscovery];
1663 [peripheral discoverDescriptorsForCharacteristic:next];
1665 [self readDescriptors:characteristic.service];
1669- (
void)peripheral:(CBPeripheral *)aPeripheral
1670 didUpdateValueForDescriptor:(CBDescriptor *)descriptor
1671 error:(NSError *)error
1673 Q_UNUSED(aPeripheral);
1675 Q_ASSERT_X(peripheral, Q_FUNC_INFO,
"invalid peripheral (nil)");
1684 using namespace DarwinBluetooth;
1686 if (![self objectIsUnderWatch:descriptor operation:OperationTimeout::descriptorRead])
1689 [self stopWatchingAfter:descriptor operation:OperationTimeout::descriptorRead];
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);
1697 NSLog(@
"%s failed with error %@", Q_FUNC_INFO, error);
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];
1711 if (isDetailsDiscovery) {
1713 CBDescriptor *
const next = [self nextDescriptorForCharacteristic:descriptor.characteristic
1714 startingFrom:descriptor];
1716 [self watchAfter:next timeout:OperationTimeout::descriptorRead];
1717 [peripheral readValueForDescriptor:next];
1722 CBCharacteristic *
const ch = descriptor.characteristic;
1723 CBCharacteristic *nextCh = [self nextCharacteristicForService:ch.service
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];
1732 nextCh = [self nextCharacteristicForService:ch.service
1733 startingFrom:nextCh];
1736 [self serviceDetailsDiscoveryFinished:service];
1740 qCCritical(QT_BT_DARWIN) <<
"unexpected value update notification, "
1741 "no descriptor handle found";
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];
1754- (
void)peripheral:(CBPeripheral *)aPeripheral
1755 didWriteValueForCharacteristic:(CBCharacteristic *)characteristic
1756 error:(NSError *)error
1758 Q_UNUSED(aPeripheral);
1759 Q_UNUSED(characteristic);
1773 using namespace DarwinBluetooth;
1777 if (![self objectIsUnderWatch:characteristic operation:OperationTimeout::characteristicWrite])
1780 [self stopWatchingAfter:characteristic operation:OperationTimeout::characteristicWrite];
1781 requestPending =
false;
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";
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];
1796 const QLowEnergyHandle cHandle = charMap.key(characteristic);
1797 emit notifier->characteristicWritten(cHandle, valueToReport);
1800 [self performNextRequest];
1803- (
void)peripheral:(CBPeripheral *)aPeripheral
1804 didWriteValueForDescriptor:(CBDescriptor *)descriptor
1805 error:(NSError *)error
1807 Q_UNUSED(aPeripheral);
1814 using namespace DarwinBluetooth;
1818 requestPending =
false;
1821 const QByteArray valueToReport(valuesToWrite.value(descriptor, QByteArray()));
1822 if (!valuesToWrite.remove(descriptor))
1823 qCWarning(QT_BT_DARWIN) <<
"no updated value found";
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];
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);
1836 [self performNextRequest];
1839- (
void)peripheral:(CBPeripheral *)aPeripheral
1840 didUpdateNotificationStateForCharacteristic:(CBCharacteristic *)characteristic
1841 error:(NSError *)error
1843 Q_UNUSED(aPeripheral);
1848 using namespace DarwinBluetooth;
1852 requestPending =
false;
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);
1860 NSLog(@
"%s failed with error %@", Q_FUNC_INFO, error);
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);
1869 [self performNextRequest];
1872- (
void)peripheral:(CBPeripheral *)aPeripheral didReadRSSI:(NSNumber *)RSSI error:(nullable NSError *)error
1874 Q_UNUSED(aPeripheral);
1880 NSLog(@
"Reading RSSI finished with error: %@", error);
1881 return emit notifier->CBManagerError(QLowEnergyController::RssiReadError);
1885 qCWarning(QT_BT_DARWIN,
"Reading RSSI returned no value");
1886 return emit notifier->CBManagerError(QLowEnergyController::RssiReadError);
1889 emit notifier->rssiUpdated(qint16([RSSI shortValue]));
1895 notifier->disconnect();
1896 notifier->deleteLater();
1900 [self stopWatchers];
1901 [self disconnectFromDevice];
#define QT_BT_MAC_AUTORELEASEPOOL
ObjCStrongReference< NSError > qt_timeoutNSError(OperationTimeout type)
auto qt_find_watchdog(const std::vector< GCDTimer > &watchdogs, id object, OperationTimeout type)
NSUInteger qt_countGATTEntries(CBService *service)