7#include <QtBluetooth/qbluetoothlocaldevice.h>
8#include <QtBluetooth/QLowEnergyCharacteristicData>
9#include <QtBluetooth/QLowEnergyDescriptorData>
10#include <QtBluetooth/private/qbluetoothutils_winrt_p.h>
11#include <QtBluetooth/QLowEnergyService>
13#include <QtCore/QtEndian>
14#include <QtCore/QLoggingCategory>
15#include <QtCore/private/qfunctions_winrt_p.h>
16#include <QtCore/QDeadlineTimer>
17#include <QtCore/qpointer.h>
18#include <QtCore/QAbstractEventDispatcher>
19#include <QtCore/QDeadlineTimer>
24#include <winrt/Windows.Foundation.h>
25#include <winrt/Windows.Foundation.Collections.h>
26#include <winrt/Windows.Foundation.Metadata.h>
27#include <winrt/Windows.Devices.Enumeration.h>
28#include <winrt/Windows.Devices.Bluetooth.h>
29#include <winrt/Windows.Devices.Bluetooth.GenericAttributeProfile.h>
30#include <winrt/Windows.Storage.Streams.h>
32#include <windows.devices.bluetooth.h>
33#include <windows.devices.bluetooth.genericattributeprofile.h>
36using namespace winrt::Windows::Foundation;
37using namespace winrt::Windows::Foundation::Collections;
38using namespace winrt::Windows::Devices;
39using namespace winrt::Windows::Devices::Bluetooth;
40using namespace winrt::Windows::Devices::Bluetooth::GenericAttributeProfile;
41using namespace winrt::Windows::Devices::Enumeration;
42using namespace winrt::Windows::Storage::Streams;
51 std::enable_if_t<std::is_enum_v<E>,
int> = 0>
54 return static_cast<std::underlying_type_t<E>>(x) &
static_cast<std::underlying_type_t<E>>(y);
57template<
typename T,
typename E,
58 std::enable_if_t<std::conjunction_v<std::is_integral<T>, std::is_enum<E>>,
int> = 0>
61 return x &
static_cast<std::underlying_type_t<E>>(y);
65 std::enable_if_t<std::is_enum_v<E>,
int> = 0>
68 return static_cast<std::underlying_type_t<E>>(x) |
static_cast<std::underlying_type_t<E>>(y);
71template<
typename T,
typename E,
72 std::enable_if_t<std::conjunction_v<std::is_integral<T>, std::is_enum<E>>,
int> = 0>
75 return x |
static_cast<std::underlying_type_t<E>>(y);
78template<
typename T,
typename E,
79 std::enable_if_t<std::conjunction_v<std::is_integral<T>, std::is_enum<E>>,
int> = 0>
82 a |=
static_cast<std::underlying_type_t<E>>(b);
86#define ENUM_BITWISE_OPS(E) inline
87 constexpr std::underlying_type_t<E> operator
&(E x, E y) { return bitwise_and<E>(x, y); } template
90 constexpr T operator
&(T x, E y) { return bitwise_and<T, E>(x, y); } template
93 constexpr T operator
&(E x, T y) { return bitwise_and<T, E>(y, x); } inline
95 constexpr std::underlying_type_t<E> operator
|(E x, E y) { return bitwise_or<E>(x, y); } template
98 constexpr T operator
|(T x, E y) { return bitwise_or<T, E>(x, y); } template
101 constexpr T operator
|(E x, T y) { return bitwise_or<T, E>(y, x); } template
104 constexpr T &operator
|=(T &a, const E &b) { return bitwise_or_equal(a, b); }
113static constexpr bool never() {
return false; }
118 QDeadlineTimer awaitTime(timeout);
120 QThread::yieldCurrentThread();
121 if (asyncInfo.Status() != winrt::AsyncStatus::Started) {
122 check_hresult(asyncInfo.ErrorCode());
123 return asyncInfo.GetResults();
125 QCoreApplication::processEvents(QEventLoop::AllEvents);
126 }
while (!canceled() && !awaitTime.hasExpired());
128 throw hresult_error(E_ABORT);
139#define WARN_AND_CONTINUE(msg)
141 qCWarning(QT_BT_WINDOWS) << msg;
145#define DEC_CHAR_COUNT_AND_CONTINUE(msg)
147 qCWarning(QT_BT_WINDOWS) << msg;
148 --mCharacteristicsCountToBeDiscovered;
152#define RETURN_SERVICE_ERROR(msg, service, error)
154 qCDebug(QT_BT_WINDOWS) << msg;
155 service->setError(error);
159#define RETURN_FALSE(msg)
165#define RETURN_MSG(msg)
171Q_DECLARE_LOGGING_CATEGORY(QT_BT_WINDOWS)
172Q_DECLARE_LOGGING_CATEGORY(QT_BT_WINDOWS_SERVICE_THREAD)
174static constexpr qint64 kMaxConnectTimeout = 20000;
179 qErrnoWarning(
"nullptr passed to byteArrayFromBuffer");
182 qsizetype size =
SAFE(buffer.Length());
186 QString valueString = QString::fromUtf16(
187 reinterpret_cast<
char16_t *>(buffer.data())).left(size / 2);
188 return valueString.toUtf8();
190 return QByteArray(
reinterpret_cast<
char *>(buffer.data()), size);
194 bool isWCharString =
false)
196 auto buffer =
SAFE(gattResult.Value());
198 qCWarning(QT_BT_WINDOWS) <<
"Could not obtain buffer from GattReadResult";
201 return byteArrayFromBuffer(buffer, isWCharString);
376 void emitErrorAndQuitThread(
const QString &error);
399 if (!mAbortRequested && (mCharacteristicsCountToBeDiscovered == 0)) {
400 emit charListObtained(mService, mCharacteristicList, mIndicateChars,
401 mStartHandle, mEndHandle);
403 QThread::currentThread()->quit();
409 emit errorOccured(error);
410 QThread::currentThread()->quit();
444 void connectToPairedDevice();
445 void connectToUnpairedDevice();
446 void emitErrorAndQuitThread(
const QString &error);
447 void emitErrorAndQuitThread(
const char *error);
448 void emitConnectedAndQuitThread();
450 BluetoothLEDevice mDevice =
nullptr;
451 GattSession mGattSession =
nullptr;
452 const QBluetoothAddress mAddress;
453 bool mAbortConnection =
false;
454 bool mComInitialized =
false;
459 qCDebug(QT_BT_WINDOWS) <<
__FUNCTION__;
460 mComInitialized =
TRY(winrt::init_apartment());
462 auto earlyExit = [
this]() {
return mAbortConnection; };
463 if (!(mDevice =
SAFE(await(BluetoothLEDevice::FromBluetoothAddressAsync(mAddress.toUInt64()), earlyExit))))
464 return emitErrorAndQuitThread(
"Could not find LE device from address");
467 BluetoothDeviceId deviceId =
SAFE(mDevice.BluetoothDeviceId());
469 return emitErrorAndQuitThread(
"Could not get device id");
472 if (!(mGattSession =
SAFE(await(GattSession::FromDeviceIdAsync(deviceId), earlyExit))))
473 return emitErrorAndQuitThread(
"Could not get GattSession from id");
475 BluetoothConnectionStatus status;
476 if (!
TRY(status = mDevice.ConnectionStatus()))
477 return emitErrorAndQuitThread(
"Could not get connection status");
478 if (status == BluetoothConnectionStatus::Connected)
479 return emitConnectedAndQuitThread();
481 QBluetoothLocalDevice localDevice;
482 QBluetoothLocalDevice::Pairing pairing = localDevice.pairingStatus(mAddress);
483 if (pairing == QBluetoothLocalDevice::Unpaired)
484 connectToUnpairedDevice();
486 connectToPairedDevice();
491 mAbortConnection =
true;
496 disconnect(
this, &QWinRTLowEnergyConnectionHandler::deviceConnected,
nullptr,
nullptr);
497 disconnect(
this, &QWinRTLowEnergyConnectionHandler::errorOccurred,
nullptr,
nullptr);
502 auto earlyExit = [
this]() {
return mAbortConnection; };
503 QDeadlineTimer deadline(kMaxConnectTimeout);
504 while (!mAbortConnection && !deadline.hasExpired()) {
506 auto deviceServicesResult =
SAFE(await(mDevice.GetGattServicesAsync(), earlyExit));
507 if (!deviceServicesResult)
508 return emitErrorAndQuitThread(
"Could not obtain services");
510 if (!
SAFE(deviceServicesResult.Status() == GattCommunicationStatus::Success))
511 return emitErrorAndQuitThread(
"Service operation failed");
513 auto deviceServices =
SAFE(deviceServicesResult.Services());
515 return emitErrorAndQuitThread(
"Could not obtain list of services");
518 if (!
TRY(serviceCount = deviceServices.Size()))
519 return emitErrorAndQuitThread(
"Could not obtain size of list of services");
520 if (serviceCount == 0)
521 return emitErrorAndQuitThread(
"Found devices without services");
525 for (uint i = 0; i < serviceCount; ++i) {
527 auto service =
SAFE(deviceServices.GetAt(i));
529 return emitErrorAndQuitThread(
"Could not obtain service");
531 auto characteristicsResult =
SAFE(await(service.GetCharacteristicsAsync(), earlyExit));
532 if (!characteristicsResult)
533 return emitErrorAndQuitThread(
"Could not obtain characteristic");
535 if (!
SAFE(characteristicsResult.Status() == GattCommunicationStatus::Success)) {
536 qCWarning(QT_BT_WINDOWS) <<
"Characteristic operation failed";
540 IVectorView<GattCharacteristic> characteristics =
nullptr;
541 auto hr =
HR(characteristics = characteristicsResult.Characteristics());
542 if (hr == E_ACCESSDENIED) {
545 return emitErrorAndQuitThread(
"Could not obtain characteristic list. "
546 "Please check your manifest capabilities");
547 }
else if (FAILED(hr) || !characteristics) {
548 return emitErrorAndQuitThread(
"Could not obtain characteristic list.");
551 uint characteristicsCount;
552 if (!
TRY(characteristicsCount = characteristics.Size()))
553 return emitErrorAndQuitThread(
"Could not obtain size of characteristic list.");
554 for (uint j = 0; j < characteristicsCount; ++j) {
556 auto characteristic =
SAFE(characteristics.GetAt(j));
558 return emitErrorAndQuitThread(
"Could not get characteristic");
559 GattReadResult result =
nullptr;
560 hr =
HR(result = await(
561 characteristic.ReadValueAsync(BluetoothCacheMode::Uncached), earlyExit));
562 if (hr == E_ILLEGAL_METHOD_CALL) {
566 }
else if (FAILED(hr) || !result) {
567 return emitErrorAndQuitThread(
"Could not read characteristic value");
570 auto buffer =
SAFE(result.Value());
572 qCDebug(QT_BT_WINDOWS) <<
"Problem reading value";
576 emitConnectedAndQuitThread();
584 emitErrorAndQuitThread(
"Connect to device failed due to timeout!");
589 qCDebug(QT_BT_WINDOWS) <<
__FUNCTION__;
591 auto earlyExit = [
this]() {
return mAbortConnection; };
592 QDeadlineTimer deadline(kMaxConnectTimeout);
593 while (!mAbortConnection && !deadline.hasExpired()) {
595 auto deviceServicesResult =
SAFE(await_forever(mDevice.GetGattServicesAsync(), earlyExit));
596 if (!deviceServicesResult)
597 return emitErrorAndQuitThread(
"Could not obtain services");
599 GattCommunicationStatus commStatus;
600 if (!
TRY(commStatus = deviceServicesResult.Status()))
601 return emitErrorAndQuitThread(
"Could not obtain comm status");
602 if (commStatus == GattCommunicationStatus::Unreachable)
604 if (commStatus != GattCommunicationStatus::Success)
605 return emitErrorAndQuitThread(
"Service operation failed");
607 emitConnectedAndQuitThread();
613 emitErrorAndQuitThread(
"Connect to device failed due to timeout!");
618 emit errorOccurred(error);
619 QThread::currentThread()->quit();
624 emitErrorAndQuitThread(QString::fromUtf8(error));
629 emit deviceConnected(mDevice.as<abi::BluetoothLEDevice>(), mGattSession.as<abi::GattSession>());
630 QThread::currentThread()->quit();
633QLowEnergyControllerPrivateWinRT::QLowEnergyControllerPrivateWinRT()
637 connect(
this, &QLowEnergyControllerPrivateWinRT::characteristicChanged,
638 this, &QLowEnergyControllerPrivateWinRT::handleCharacteristicChanged,
639 Qt::QueuedConnection);
644 unregisterFromStatusChanges();
645 unregisterFromValueChanges();
648void QLowEnergyControllerPrivateWinRT::
init()
654 qCDebug(QT_BT_WINDOWS) <<
__FUNCTION__;
655 if (remoteDevice.isNull()) {
656 qCWarning(QT_BT_WINDOWS) <<
"Invalid/null remote device address";
657 setError(QLowEnergyController::UnknownRemoteDeviceError);
660 setState(QLowEnergyController::ConnectingState);
663 QThread *thread =
new QThread;
664 worker->moveToThread(thread);
667 connect(thread, &QThread::started, worker, &QWinRTLowEnergyConnectionHandler::connectToDevice);
668 connect(thread, &QThread::finished, worker, &QObject::deleteLater);
669 connect(worker, &QObject::destroyed, thread, &QObject::deleteLater);
670 connect(worker, &QWinRTLowEnergyConnectionHandler::errorOccurred,
this,
671 [
this](
const QString &msg) { handleConnectionError(msg.toUtf8().constData()); });
672 connect(worker, &QWinRTLowEnergyConnectionHandler::deviceConnected,
this,
673 [
this](com_ptr<abi::BluetoothLEDevice> device, com_ptr<abi::GattSession> session) {
674 if (!device || !session) {
675 handleConnectionError(
"Failed to get device or gatt service");
678 mDevice = device.as<BluetoothLEDevice>();
679 mGattSession = session.as<GattSession>();
681 if (!registerForStatusChanges() || !registerForMtuChanges()) {
682 handleConnectionError(
"Failed to register for changes");
686 Q_Q(QLowEnergyController);
687 setState(QLowEnergyController::ConnectedState);
695 qCDebug(QT_BT_WINDOWS) <<
__FUNCTION__;
696 Q_Q(QLowEnergyController);
697 setState(QLowEnergyController::ClosingState);
698 emit abortConnection();
699 unregisterFromValueChanges();
700 unregisterFromStatusChanges();
701 unregisterFromMtuChanges();
703 mGattSession =
nullptr;
705 setState(QLowEnergyController::UnconnectedState);
706 emit q->disconnected();
709bool QLowEnergyControllerPrivateWinRT::getNativeService(
const QBluetoothUuid &serviceUuid,
710 NativeServiceCallback callback)
712 if (m_openedServices.contains(serviceUuid)) {
713 callback(m_openedServices.value(serviceUuid,
nullptr));
717 auto servicesResultOperation =
SAFE(mDevice.GetGattServicesForUuidAsync(GUID(serviceUuid)));
718 if (!servicesResultOperation)
721 QPointer<QLowEnergyControllerPrivateWinRT> thisPtr(
this);
722 bool ok =
TRY(servicesResultOperation.Completed(
723 [thisPtr, callback, serviceUuid](
724 IAsyncOperation<GattDeviceServicesResult>
const &op, winrt::AsyncStatus
const status)
727 auto getService = [&]() -> GattDeviceService {
729 qCWarning(QT_BT_WINDOWS) <<
"LE controller was removed while getting native service";
733 if (status != winrt::AsyncStatus::Completed) {
734 qCDebug(QT_BT_WINDOWS) <<
"Failed to get result of async service request";
738 auto result =
SAFE(op.GetResults());
740 qErrnoWarning(
"Failed to get result of async service request");
744 auto services =
SAFE(result.Services());
746 qErrnoWarning(
"Failed to extract services from the result");
750 uint servicesCount = 0;
751 if (!
TRY(servicesCount = services.Size())) {
752 qErrnoWarning(
"Failed to extract services count");
756 if (servicesCount == 0) {
757 qCWarning(QT_BT_WINDOWS) <<
"No services found for Uuid" << serviceUuid;
761 if (servicesCount > 1) {
762 qCWarning(QT_BT_WINDOWS)
763 <<
"getNativeService: more than one service detected for UUID"
764 << serviceUuid <<
"The first service will be used.";
767 auto service =
SAFE(services.GetAt(0));
769 qCDebug(QT_BT_WINDOWS) <<
"Could not obtain native service for Uuid"
775 auto service = getService();
779 QMetaObject::invokeMethod(thisPtr.get(),
780 [thisPtr, callback, service, serviceUuid]() {
782 thisPtr->m_openedServices.insert(serviceUuid, service);
790bool QLowEnergyControllerPrivateWinRT::getNativeCharacteristic(
791 const QBluetoothUuid &serviceUuid,
const QBluetoothUuid &charUuid,
792 NativeCharacteristicCallback callback)
795 const NativeCharacteristicKey key = std::make_pair(serviceUuid, charUuid);
796 auto cachedChar = m_openedCharacteristics.constFind(key);
797 if (cachedChar != m_openedCharacteristics.cend()) {
798 callback(cachedChar.value());
802 auto pendingIt = m_pendingCharOperations.find(key);
803 if (pendingIt != m_pendingCharOperations.end()) {
806 pendingIt->callbacks.append(
std::move(callback));
811 const quint64 generation = ++m_charOperationsGeneration;
812 m_pendingCharOperations.insert(key, { generation, { std::move(callback) } });
814 QPointer<QLowEnergyControllerPrivateWinRT> thisPtr(
this);
816 auto serviceCallback = [thisPtr, charUuid, key, generation](GattDeviceService service) {
821 auto cacheCharAndExecuteCallback = [thisPtr, key, generation](
822 GattDeviceService service,
823 GattCharacteristic characteristic) {
826 QMetaObject::invokeMethod(thisPtr.get(),
827 [thisPtr, key, generation, service, characteristic]() {
828 thisPtr->handleCharacteristic(key, generation, service,
834 cacheCharAndExecuteCallback(
nullptr,
nullptr);
838 auto characteristicRequestOp =
SAFE(service.GetCharacteristicsForUuidAsync(GUID(charUuid)));
839 if (!characteristicRequestOp) {
840 qErrnoWarning(
"Could not start async characteristics request");
841 cacheCharAndExecuteCallback(service,
nullptr);
845 const bool ok =
TRY(characteristicRequestOp.Completed(
846 [thisPtr, service, cacheCharAndExecuteCallback](
847 IAsyncOperation<GattCharacteristicsResult>
const &op, winrt::AsyncStatus
const status)
849 auto getCharacteristic = [&]() -> GattCharacteristic {
853 if (status != winrt::AsyncStatus::Completed) {
854 qCDebug(QT_BT_WINDOWS) <<
"Failed to get result of async characteristic "
859 auto result =
SAFE(op.GetResults());
861 qErrnoWarning(
"Failed to get result of async characteristic operation");
865 GattCommunicationStatus commStatus;
866 if (!
TRY(commStatus = result.Status()) || commStatus != GattCommunicationStatus::Success) {
867 qErrnoWarning(
"Native characteristic operation failed.");
871 auto characteristics =
SAFE(result.Characteristics());
872 if (!characteristics) {
873 qErrnoWarning(
"Could not obtain characteristic list.");
878 if (!
TRY(size = characteristics.Size())) {
879 qErrnoWarning(
"Could not obtain characteristic list's size.");
884 qErrnoWarning(
"More than 1 characteristic found.");
886 auto characteristic =
SAFE(characteristics.GetAt(0));
888 qErrnoWarning(
"Could not obtain first characteristic for service");
890 return characteristic;
894 cacheCharAndExecuteCallback(service, getCharacteristic());
898 qErrnoWarning(
"Characteristic request failed");
899 cacheCharAndExecuteCallback(service,
nullptr);
903 if (!getNativeService(serviceUuid, serviceCallback)) {
904 qCDebug(QT_BT_WINDOWS) <<
"Failed to get native service for" << serviceUuid;
905 m_pendingCharOperations.remove(key);
912void QLowEnergyControllerPrivateWinRT::registerForValueChanges(
const QBluetoothUuid &serviceUuid,
913 const QBluetoothUuid &charUuid)
915 qCDebug(QT_BT_WINDOWS) <<
"Registering characteristic" << charUuid <<
"in service"
916 << serviceUuid <<
"for value changes";
917 for (
const ValueChangedEntry &entry : std::as_const(mValueChangedTokens)) {
919 if (!
TRY(guuid = entry.characteristic.Uuid()))
921 if (QBluetoothUuid(guuid) == charUuid)
925 auto callback = [
this, charUuid, serviceUuid](GattCharacteristic characteristic) {
926 winrt::event_token token;
927 if (!
TRY(token = characteristic.ValueChanged({
this, &QLowEnergyControllerPrivateWinRT::onValueChange })))
928 RETURN_MSG(
"Could not register characteristic for value changes");
930 mValueChangedTokens.append(ValueChangedEntry(characteristic, token));
931 qCDebug(QT_BT_WINDOWS) <<
"Characteristic" << charUuid <<
"in service"
932 << serviceUuid <<
"registered for value changes";
935 if (!getNativeCharacteristic(serviceUuid, charUuid, callback)) {
936 qCDebug(QT_BT_WINDOWS).nospace() <<
"Could not obtain native characteristic "
937 << charUuid <<
" from service " << serviceUuid
938 <<
". Qt will not be able to signal"
939 <<
" changes for this characteristic.";
943void QLowEnergyControllerPrivateWinRT::unregisterFromValueChanges()
945 qCDebug(QT_BT_WINDOWS) <<
"Unregistering " << mValueChangedTokens.size() <<
" value change tokens";
946 for (
const ValueChangedEntry &entry : std::as_const(mValueChangedTokens)) {
947 if (!entry.characteristic) {
948 qCWarning(QT_BT_WINDOWS) <<
"Unregistering from value changes for characteristic failed."
949 <<
"Characteristic has been deleted";
952 if (!
TRY(entry.characteristic.ValueChanged(entry.token)))
953 qCWarning(QT_BT_WINDOWS) <<
"Unregistering from value changes for characteristic failed.";
955 mValueChangedTokens.clear();
958void QLowEnergyControllerPrivateWinRT::onValueChange(GattCharacteristic characteristic, GattValueChangedEventArgs
const &args)
961 if (!
TRY(handle = characteristic.AttributeHandle()))
962 RETURN_MSG(
"Could not obtain characteristic's handle");
964 auto buffer =
SAFE(args.CharacteristicValue());
966 RETURN_MSG(
"Could not obtain characteristic's value");
968 emit characteristicChanged(handle, byteArrayFromBuffer(buffer));
971bool QLowEnergyControllerPrivateWinRT::registerForMtuChanges()
973 if (!mDevice || !mGattSession)
975 qCDebug(QT_BT_WINDOWS) <<
__FUNCTION__;
977 QPointer<QLowEnergyControllerPrivateWinRT> thisPtr(
this);
978 auto mtuChangeCallback = [thisPtr](GattSession session, winrt::IInspectable args) {
981 QMetaObject::invokeMethod(thisPtr.get(), [thisPtr, session, args]() {
982 thisPtr->onMtuChange(session, args);
986 if (!
TRY(mMtuChangedToken = mGattSession.MaxPduSizeChanged(mtuChangeCallback)))
991void QLowEnergyControllerPrivateWinRT::unregisterFromMtuChanges()
993 qCDebug(QT_BT_WINDOWS) <<
__FUNCTION__;
994 if (mDevice && mGattSession && mMtuChangedToken) {
995 TRY(mGattSession.MaxPduSizeChanged(mMtuChangedToken));
996 mMtuChangedToken = { 0 };
1000void QLowEnergyControllerPrivateWinRT::onMtuChange(GattSession session, winrt::IInspectable args)
1002 qCDebug(QT_BT_WINDOWS) <<
__FUNCTION__;
1004 if (session != mGattSession) {
1005 qCWarning(QT_BT_WINDOWS) <<
"Got MTU changed event for wrong or outdated GattSession.";
1007 Q_Q(QLowEnergyController);
1008 emit q->mtuChanged(mtu());
1012bool QLowEnergyControllerPrivateWinRT::registerForStatusChanges()
1017 qCDebug(QT_BT_WINDOWS) <<
__FUNCTION__;
1019 QPointer<QLowEnergyControllerPrivateWinRT> thisPtr(
this);
1020 auto statusChangeCallback = [thisPtr](BluetoothLEDevice dev, winrt::IInspectable args) {
1023 QMetaObject::invokeMethod(thisPtr.get(), [thisPtr, dev, args]() {
1024 thisPtr->onStatusChange(dev, args);
1028 if (!
TRY(mStatusChangedToken = mDevice.ConnectionStatusChanged(statusChangeCallback)))
1033void QLowEnergyControllerPrivateWinRT::unregisterFromStatusChanges()
1035 qCDebug(QT_BT_WINDOWS) <<
__FUNCTION__;
1036 if (mDevice && mStatusChangedToken) {
1037 TRY(mDevice.ConnectionStatusChanged(mStatusChangedToken));
1038 mStatusChangedToken = { 0 };
1042void QLowEnergyControllerPrivateWinRT::onStatusChange(BluetoothLEDevice dev, winrt::IInspectable args)
1044 Q_Q(QLowEnergyController);
1046 BluetoothConnectionStatus status;
1047 if (!
TRY(status = dev.ConnectionStatus()))
1048 RETURN_MSG(
"Could not obtain connection status");
1050 if (state == QLowEnergyController::ConnectingState
1051 && status == BluetoothConnectionStatus::Connected) {
1052 setState(QLowEnergyController::ConnectedState);
1053 emit q->connected();
1054 }
else if (state != QLowEnergyController::UnconnectedState
1055 && status == BluetoothConnectionStatus::Disconnected) {
1057 unregisterFromValueChanges();
1058 unregisterFromStatusChanges();
1059 unregisterFromMtuChanges();
1061 mGattSession =
nullptr;
1063 setError(QLowEnergyController::RemoteHostClosedError);
1064 setState(QLowEnergyController::UnconnectedState);
1065 emit q->disconnected();
1069void QLowEnergyControllerPrivateWinRT::obtainIncludedServices(QSharedPointer<QLowEnergyServicePrivate> servicePointer, GattDeviceService service)
1071 Q_Q(QLowEnergyController);
1073 auto result =
SAFE(await(service.GetIncludedServicesAsync()));
1075 RETURN_MSG(
"Could not obtain included services");
1078 if (state != QLowEnergyController::DiscoveringState)
1081 GattCommunicationStatus status;
1082 if (!
TRY(status = result.Status())) {
1083 qErrnoWarning(
"Could not obtain list of included services");
1087 auto includedServices =
SAFE(result.Services());
1088 if (!includedServices)
1092 if (!
TRY(count = includedServices.Size()))
1093 RETURN_MSG(
"Could not obtain service list's size");
1095 for (uint i = 0; i < count; ++i) {
1097 auto includedService =
SAFE(includedServices.GetAt(i));
1098 if (!includedService)
1102 if (!
TRY(guuid = includedService.Uuid()))
1105 const QBluetoothUuid includedUuid(guuid);
1106 QSharedPointer<QLowEnergyServicePrivate> includedPointer;
1107 qCDebug(QT_BT_WINDOWS_SERVICE_THREAD) <<
__FUNCTION__
1108 <<
"Changing service pointer from thread"
1109 << QThread::currentThread();
1110 if (serviceList.contains(includedUuid)) {
1111 includedPointer = serviceList.value(includedUuid);
1114 priv->uuid = includedUuid;
1118 serviceList.insert(includedUuid, includedPointer);
1120 includedPointer->type |= QLowEnergyService::IncludedService;
1121 servicePointer->includedServices.append(includedUuid);
1123 obtainIncludedServices(includedPointer, includedService);
1125 emit q->serviceDiscovered(includedUuid);
1129void QLowEnergyControllerPrivateWinRT::onServiceDiscoveryFinished(IAsyncOperation<GattDeviceServicesResult>
const &op, winrt::AsyncStatus status)
1137 if (state != QLowEnergyController::DiscoveringState)
1140 Q_Q(QLowEnergyController);
1141 if (status != winrt::AsyncStatus::Completed) {
1142 qCDebug(QT_BT_WINDOWS) <<
"Could not obtain services";
1146 auto result =
SAFE(op.GetResults());
1148 return handleConnectionError(
"Could not obtain service discovery result");
1150 GattCommunicationStatus commStatus;
1151 if (!
TRY(commStatus = result.Status()))
1152 return handleConnectionError(
"Could not obtain service discovery status");
1154 if (commStatus != GattCommunicationStatus::Success)
1157 auto deviceServices =
SAFE(result.Services());
1158 if (!deviceServices)
1159 return handleConnectionError(
"Could not obtain service list");
1162 if (!
TRY(serviceCount = deviceServices.Size()))
1163 return handleConnectionError(
"Could not obtain service list size");
1165 for (uint i = 0; i < serviceCount; ++i) {
1167 auto deviceService =
SAFE(deviceServices.GetAt(i));
1172 if (!
TRY(guuid = deviceService.Uuid()))
1175 const QBluetoothUuid service(guuid);
1176 m_openedServices.insert(service, deviceService);
1178 qCDebug(QT_BT_WINDOWS_SERVICE_THREAD) <<
__FUNCTION__
1179 <<
"Changing service pointer from thread"
1180 << QThread::currentThread();
1181 QSharedPointer<QLowEnergyServicePrivate> pointer;
1182 if (serviceList.contains(service)) {
1183 pointer = serviceList.value(service);
1186 priv->uuid = service;
1190 serviceList.insert(service, pointer);
1192 pointer->type |= QLowEnergyService::PrimaryService;
1194 obtainIncludedServices(pointer, deviceService);
1198 if (state != QLowEnergyController::DiscoveringState) {
1199 emit q->discoveryFinished();
1204 emit q->serviceDiscovered(service);
1207 setState(QLowEnergyController::DiscoveredState);
1208 emit q->discoveryFinished();
1211void QLowEnergyControllerPrivateWinRT::clearAllServices()
1215 for (
auto &uuid : m_requestDetailsServiceUuids)
1216 m_openedServices.remove(uuid);
1217 m_requestDetailsServiceUuids.clear();
1219 for (
auto service : m_openedServices)
1220 TRY(service.Close());
1221 m_openedServices.clear();
1222 m_openedCharacteristics.clear();
1223 m_pendingCharOperations.clear();
1226void QLowEnergyControllerPrivateWinRT::closeAndRemoveService(
const QBluetoothUuid &uuid)
1228 auto record = m_openedServices.find(uuid);
1229 if (record != m_openedServices.end()) {
1230 auto service = record.value();
1231 m_openedServices.erase(record);
1233 TRY(service.Close());
1235 removeCachedCharacteristics(uuid);
1238void QLowEnergyControllerPrivateWinRT::handleCharacteristic(
const NativeCharacteristicKey &key,
1240 GattDeviceService service,
1241 GattCharacteristic characteristic)
1243 auto pendingOpIt = m_pendingCharOperations.find(key);
1244 if (pendingOpIt == m_pendingCharOperations.end() || pendingOpIt->generation != generation) {
1250 const QList<NativeCharacteristicCallback> callbacks =
std::move(pendingOpIt->callbacks);
1251 m_pendingCharOperations.erase(pendingOpIt);
1252 if (!characteristic)
1256 auto serviceIt = m_openedServices.constFind(key.first);
1257 if (serviceIt != m_openedServices.cend() && serviceIt.value() == service)
1258 m_openedCharacteristics.insert(key, characteristic);
1261 for (
const auto &callback : callbacks)
1262 callback(characteristic);
1265void QLowEnergyControllerPrivateWinRT::removeCachedCharacteristics(
const QBluetoothUuid &serviceUuid)
1270 auto it = m_openedCharacteristics.begin();
1271 while (it != m_openedCharacteristics.end()) {
1272 if (it.key().first == serviceUuid)
1273 it = m_openedCharacteristics.erase(it);
1281 qCDebug(QT_BT_WINDOWS) <<
"Service discovery initiated";
1285 auto asyncResult =
SAFE(mDevice.GetGattServicesAsync());
1287 return handleConnectionError(
"Could not obtain services");
1289 QPointer<QLowEnergyControllerPrivateWinRT> thisPtr(
this);
1290 auto discoveryCallback = [thisPtr](IAsyncOperation<GattDeviceServicesResult>
const &op,
1291 winrt::AsyncStatus status) {
1294 QMetaObject::invokeMethod(thisPtr.get(), [thisPtr, op, status]() {
1295 thisPtr->onServiceDiscoveryFinished(op, status);
1299 if (!
TRY(asyncResult.Completed(discoveryCallback)))
1300 return handleConnectionError(
"Could not register services discovery callback");
1304 const QBluetoothUuid &service, QLowEnergyService::DiscoveryMode mode)
1306 qCDebug(QT_BT_WINDOWS) <<
__FUNCTION__ << service;
1307 if (!serviceList.contains(service)) {
1308 qCWarning(QT_BT_WINDOWS) <<
"Discovery done of unknown service:"
1309 << service.toString();
1314 closeAndRemoveService(service);
1316 auto serviceCallback = [service, mode,
this](GattDeviceService deviceService) {
1317 discoverServiceDetailsHelper(service, mode, deviceService);
1320 if (!getNativeService(service, serviceCallback))
1321 qCDebug(QT_BT_WINDOWS) <<
"Could not obtain native service for uuid " << service;
1324void QLowEnergyControllerPrivateWinRT::discoverServiceDetailsHelper(
1325 const QBluetoothUuid &service, QLowEnergyService::DiscoveryMode mode,
1326 GattDeviceService deviceService)
1328 auto reactOnDiscoveryError = [](QSharedPointer<QLowEnergyServicePrivate> service,
1331 qCDebug(QT_BT_WINDOWS) << msg;
1332 service->setError(QLowEnergyService::UnknownError);
1333 service->setState(QLowEnergyService::RemoteService);
1336 QSharedPointer<QLowEnergyServicePrivate> pointer = serviceList.value(service);
1338 qCDebug(QT_BT_WINDOWS) <<
"Device was disconnected while doing service discovery";
1341 qCDebug(QT_BT_WINDOWS_SERVICE_THREAD) <<
__FUNCTION__ <<
"Changing service pointer from thread"
1342 << QThread::currentThread();
1344 return reactOnDiscoveryError(pointer,
"Device service was not discovered");
1346 pointer->setState(QLowEnergyService::RemoteServiceDiscovering);
1348 auto result =
SAFE(await_forever(deviceService.GetIncludedServicesAsync()));
1350 return reactOnDiscoveryError(pointer,
"Could not obtain included service list");
1352 if (
SAFE(result.Status() != GattCommunicationStatus::Success))
1353 return reactOnDiscoveryError(pointer,
"Obtaining list of included services failed");
1355 auto deviceServices =
SAFE(result.Services());
1356 if (!deviceServices)
1357 return reactOnDiscoveryError(pointer,
"Could not obtain service list from result");
1360 if (!
TRY(serviceCount = deviceServices.Size()))
1361 return reactOnDiscoveryError(pointer,
"Could not obtain included service list's size");
1363 for (uint i = 0; i < serviceCount; ++i) {
1365 auto includedService =
SAFE(deviceServices.GetAt(i));
1366 if (!includedService)
1370 if (!
TRY(guuid = includedService.Uuid()))
1373 const QBluetoothUuid service(guuid);
1374 if (service.isNull()) {
1375 qCDebug(QT_BT_WINDOWS) <<
"Could not find service";
1379 pointer->includedServices.append(service);
1382 QSharedPointer<QLowEnergyServicePrivate> otherService = serviceList.value(service);
1383 if (!otherService.isNull())
1384 otherService->type |= QLowEnergyService::IncludedService;
1389 m_requestDetailsServiceUuids.insert(service);
1390 QThread *thread =
new QThread;
1391 worker->moveToThread(thread);
1392 connect(thread, &QThread::started, worker, &QWinRTLowEnergyServiceHandler::obtainCharList);
1393 connect(thread, &QThread::finished, worker, &QObject::deleteLater);
1394 connect(worker, &QObject::destroyed, thread, &QObject::deleteLater);
1396 worker, &QWinRTLowEnergyServiceHandler::setAbortRequested);
1397 connect(worker, &QWinRTLowEnergyServiceHandler::errorOccured,
1398 this, &QLowEnergyControllerPrivateWinRT::handleServiceHandlerError);
1399 connect(worker, &QWinRTLowEnergyServiceHandler::charListObtained,
this,
1400 [
this](
const QBluetoothUuid &service, QHash<QLowEnergyHandle,
1401 QLowEnergyServicePrivate::CharData> charList, QList<QBluetoothUuid> indicateChars,
1402 QLowEnergyHandle startHandle, QLowEnergyHandle endHandle) {
1403 if (!serviceList.contains(service)) {
1404 qCWarning(QT_BT_WINDOWS)
1405 <<
"Discovery complete for unknown service:" << service.toString();
1408 m_requestDetailsServiceUuids.remove(service);
1410 QSharedPointer<QLowEnergyServicePrivate> pointer = serviceList.value(service);
1411 pointer->startHandle = startHandle;
1412 pointer->endHandle = endHandle;
1413 pointer->characteristicList = charList;
1415 for (
const QBluetoothUuid &indicateChar : std::as_const(indicateChars))
1416 registerForValueChanges(service, indicateChar);
1418 pointer->setState(QLowEnergyService::RemoteServiceDiscovered);
1424 const QLowEnergyAdvertisingParameters &,
1425 const QLowEnergyAdvertisingData &,
1426 const QLowEnergyAdvertisingData &)
1428 setError(QLowEnergyController::AdvertisingError);
1443 const QSharedPointer<QLowEnergyServicePrivate> service,
1444 const QLowEnergyHandle charHandle)
1446 qCDebug(QT_BT_WINDOWS) <<
__FUNCTION__ << service << charHandle;
1447 qCDebug(QT_BT_WINDOWS_SERVICE_THREAD) <<
__FUNCTION__ <<
"Changing service pointer from thread"
1448 << QThread::currentThread();
1449 Q_ASSERT(!service.isNull());
1450 if (role == QLowEnergyController::PeripheralRole) {
1451 service->setError(QLowEnergyService::CharacteristicReadError);
1456 if (!service->characteristicList.contains(charHandle)) {
1457 qCDebug(QT_BT_WINDOWS) << charHandle <<
"could not be found in service" << service->uuid;
1458 service->setError(QLowEnergyService::CharacteristicReadError);
1462 const auto charData = service->characteristicList.value(charHandle);
1463 if (!(charData.properties & QLowEnergyCharacteristic::Read))
1464 qCDebug(QT_BT_WINDOWS) <<
"Read flag is not set for characteristic" << charData.uuid;
1466 auto characteristicCallback = [charHandle, service,
this](
1467 GattCharacteristic characteristic) {
1468 readCharacteristicHelper(service, charHandle, characteristic);
1471 if (!getNativeCharacteristic(service->uuid, charData.uuid, characteristicCallback)) {
1472 qCDebug(QT_BT_WINDOWS) <<
"Could not obtain native characteristic" << charData.uuid
1473 <<
"from service" << service->uuid;
1474 service->setError(QLowEnergyService::CharacteristicReadError);
1478void QLowEnergyControllerPrivateWinRT::readCharacteristicHelper(
1479 const QSharedPointer<QLowEnergyServicePrivate> service,
1480 const QLowEnergyHandle charHandle,
1481 GattCharacteristic characteristic)
1483 auto readOp =
SAFE(characteristic.ReadValueAsync(BluetoothCacheMode::Uncached));
1485 RETURN_SERVICE_ERROR(
"Could not read characteristic", service, QLowEnergyService::CharacteristicReadError);
1487 auto readCompletedLambda = [charHandle, service]
1488 (IAsyncOperation<GattReadResult>
const &op, winrt::AsyncStatus
const status)
1490 if (status == winrt::AsyncStatus::Canceled || status == winrt::AsyncStatus::Error) {
1491 qCDebug(QT_BT_WINDOWS) <<
"Characteristic" << charHandle <<
"read operation failed.";
1492 service->setError(QLowEnergyService::CharacteristicReadError);
1495 auto characteristicValue =
SAFE(op.GetResults());
1496 if (!characteristicValue)
1497 RETURN_SERVICE_ERROR(
"Could not obtain result for characteristic", service, QLowEnergyService::CharacteristicReadError);
1499 const QByteArray value = byteArrayFromGattResult(characteristicValue);
1500 auto charData = service->characteristicList.value(charHandle);
1501 charData.value = value;
1502 service->characteristicList.insert(charHandle, charData);
1503 emit service->characteristicRead(QLowEnergyCharacteristic(service, charHandle), value);
1507 if (!
TRY(readOp.Completed(readCompletedLambda)))
1508 RETURN_SERVICE_ERROR(
"Could not register characteristic read callback", service, QLowEnergyService::CharacteristicReadError);
1512 const QSharedPointer<QLowEnergyServicePrivate> service,
1513 const QLowEnergyHandle charHandle,
1514 const QLowEnergyHandle descHandle)
1516 qCDebug(QT_BT_WINDOWS) <<
__FUNCTION__ << service << charHandle << descHandle;
1517 qCDebug(QT_BT_WINDOWS_SERVICE_THREAD) <<
__FUNCTION__ <<
"Changing service pointer from thread"
1518 << QThread::currentThread();
1519 Q_ASSERT(!service.isNull());
1520 if (role == QLowEnergyController::PeripheralRole) {
1521 service->setError(QLowEnergyService::DescriptorReadError);
1526 if (!service->characteristicList.contains(charHandle)) {
1527 qCDebug(QT_BT_WINDOWS) <<
"Descriptor" << descHandle <<
"in characteristic" << charHandle
1528 <<
"cannot be found in service" << service->uuid;
1529 service->setError(QLowEnergyService::DescriptorReadError);
1533 const auto charData = service->characteristicList.value(charHandle);
1535 auto characteristicCallback = [charHandle, descHandle, service,
this](
1536 GattCharacteristic characteristic) {
1537 readDescriptorHelper(service, charHandle, descHandle, characteristic);
1540 if (!getNativeCharacteristic(service->uuid, charData.uuid, characteristicCallback)) {
1541 qCDebug(QT_BT_WINDOWS) <<
"Could not obtain native characteristic" << charData.uuid
1542 <<
"from service" << service->uuid;
1543 service->setError(QLowEnergyService::DescriptorReadError);
1547void QLowEnergyControllerPrivateWinRT::readDescriptorHelper(
1548 const QSharedPointer<QLowEnergyServicePrivate> service,
1549 const QLowEnergyHandle charHandle,
1550 const QLowEnergyHandle descHandle,
1551 GattCharacteristic characteristic)
1554 const auto charData = service->characteristicList.value(charHandle);
1555 if (!charData.descriptorList.contains(descHandle)) {
1556 qCDebug(QT_BT_WINDOWS) <<
"Descriptor" << descHandle <<
"cannot be found in characteristic"
1559 const auto descData = charData.descriptorList.value(descHandle);
1560 const QBluetoothUuid descUuid = descData.uuid;
1562 QBluetoothUuid(QBluetoothUuid::DescriptorType::ClientCharacteristicConfiguration)) {
1564 auto readOp =
SAFE(characteristic.ReadClientCharacteristicConfigurationDescriptorAsync());
1566 RETURN_SERVICE_ERROR(
"Could not read client characteristic configuration", service, QLowEnergyService::DescriptorReadError);
1568 auto readCompletedLambda = [charHandle, descHandle, service]
1569 (IAsyncOperation<ClientCharConfigDescriptorResult>
const &op, winrt::AsyncStatus
const status)
1571 if (status == winrt::AsyncStatus::Canceled || status == winrt::AsyncStatus::Error) {
1572 qCDebug(QT_BT_WINDOWS) <<
"Descriptor" << descHandle <<
"read operation failed";
1573 service->setError(QLowEnergyService::DescriptorReadError);
1577 auto iValue =
SAFE(op.GetResults());
1579 RETURN_SERVICE_ERROR(
"Could not obtain result for descriptor", service, QLowEnergyService::DescriptorReadError);
1580 GattClientCharacteristicConfigurationDescriptorValue value;
1581 if (!
TRY(value = iValue.ClientCharacteristicConfigurationDescriptor()))
1582 RETURN_SERVICE_ERROR(
"Could not obtain value for descriptor", service, QLowEnergyService::DescriptorReadError);
1585 bool correct =
false;
1586 if (value & GattClientCharacteristicConfigurationDescriptorValue::Indicate) {
1587 result |= QLowEnergyCharacteristic::Indicate;
1590 if (value & GattClientCharacteristicConfigurationDescriptorValue::Notify) {
1591 result |= QLowEnergyCharacteristic::Notify;
1594 if (value == GattClientCharacteristicConfigurationDescriptorValue::None)
1597 qCDebug(QT_BT_WINDOWS) <<
"Descriptor" << descHandle
1598 <<
"read operation failed. Obtained unexpected value.";
1599 service->setError(QLowEnergyService::DescriptorReadError);
1603 descData.uuid = QBluetoothUuid::DescriptorType::ClientCharacteristicConfiguration;
1604 descData.value = QByteArray(2, Qt::Uninitialized);
1605 qToLittleEndian(result, descData.value.data());
1606 service->characteristicList[charHandle].descriptorList[descHandle] = descData;
1607 emit service->descriptorRead(QLowEnergyDescriptor(service, charHandle, descHandle),
1612 if (!
TRY(readOp.Completed(readCompletedLambda)))
1613 RETURN_SERVICE_ERROR(
"Could not register descriptor read callback", service, QLowEnergyService::DescriptorReadError);
1618 auto result =
SAFE(await(characteristic.GetDescriptorsForUuidAsync(GUID(descData.uuid))));
1620 RETURN_SERVICE_ERROR(
"Could not obtain descriptor for uuid", service, QLowEnergyService::DescriptorReadError);
1622 GattCommunicationStatus commStatus;
1623 if (!
TRY(commStatus = result.Status()) || commStatus != GattCommunicationStatus::Success) {
1624 qErrnoWarning(
"Could not obtain list of descriptors");
1625 service->setError(QLowEnergyService::DescriptorReadError);
1629 auto descriptors =
SAFE(result.Descriptors());
1631 RETURN_SERVICE_ERROR(
"Could not obtain descriptor list", service, QLowEnergyService::DescriptorReadError);
1634 if (!
TRY(size = descriptors.Size()))
1635 RETURN_SERVICE_ERROR(
"Could not obtain descriptor list size", service, QLowEnergyService::DescriptorReadError);
1638 qCWarning(QT_BT_WINDOWS) <<
"No descriptor with uuid" << descData.uuid <<
"was found.";
1639 service->setError(QLowEnergyService::DescriptorReadError);
1641 }
else if (size > 1) {
1642 qCWarning(QT_BT_WINDOWS) <<
"There is more than 1 descriptor with uuid" << descData.uuid;
1645 auto descriptor =
SAFE(descriptors.GetAt(0));
1647 RETURN_SERVICE_ERROR(
"Could not obtain descriptor from list", service, QLowEnergyService::DescriptorReadError);
1649 auto readOp =
SAFE(descriptor.ReadValueAsync(BluetoothCacheMode::Uncached));
1651 RETURN_SERVICE_ERROR(
"Could not read descriptor value", service, QLowEnergyService::DescriptorReadError);
1653 auto readCompletedLambda = [charHandle, descHandle, descUuid, service]
1654 (IAsyncOperation<GattReadResult>
const &op, winrt::AsyncStatus
const status)
1656 if (status == winrt::AsyncStatus::Canceled || status == winrt::AsyncStatus::Error) {
1657 qCDebug(QT_BT_WINDOWS) <<
"Descriptor" << descHandle <<
"read operation failed";
1658 service->setError(QLowEnergyService::DescriptorReadError);
1662 auto descriptorValue =
SAFE(op.GetResults());
1663 if (!descriptorValue) {
1664 qCDebug(QT_BT_WINDOWS) <<
"Could not obtain result for descriptor" << descHandle;
1665 service->setError(QLowEnergyService::DescriptorReadError);
1669 descData.uuid = descUuid;
1670 if (descData.uuid == QBluetoothUuid::DescriptorType::CharacteristicUserDescription)
1671 descData.value = byteArrayFromGattResult(descriptorValue,
true);
1673 descData.value = byteArrayFromGattResult(descriptorValue);
1674 service->characteristicList[charHandle].descriptorList[descHandle] = descData;
1675 emit service->descriptorRead(QLowEnergyDescriptor(service, charHandle, descHandle),
1678 if (!
TRY(readOp.Completed(readCompletedLambda)))
1679 RETURN_SERVICE_ERROR(
"Could not register descriptor read callback", service, QLowEnergyService::DescriptorReadError);
1683 const QSharedPointer<QLowEnergyServicePrivate> service,
1684 const QLowEnergyHandle charHandle,
1685 const QByteArray &newValue,
1686 QLowEnergyService::WriteMode mode)
1688 qCDebug(QT_BT_WINDOWS) <<
__FUNCTION__ << service << charHandle << newValue << mode;
1689 qCDebug(QT_BT_WINDOWS_SERVICE_THREAD) <<
__FUNCTION__ <<
"Changing service pointer from thread"
1690 << QThread::currentThread();
1691 Q_ASSERT(!service.isNull());
1692 if (role == QLowEnergyController::PeripheralRole) {
1693 service->setError(QLowEnergyService::CharacteristicWriteError);
1697 if (!service->characteristicList.contains(charHandle)) {
1698 qCDebug(QT_BT_WINDOWS) <<
"Characteristic" << charHandle <<
"cannot be found in service"
1700 service->setError(QLowEnergyService::CharacteristicWriteError);
1705 const bool writeWithResponse = mode == QLowEnergyService::WriteWithResponse;
1706 if (!(charData.properties & (writeWithResponse ? QLowEnergyCharacteristic::Write
1707 : QLowEnergyCharacteristic::WriteNoResponse)))
1708 qCDebug(QT_BT_WINDOWS) <<
"Write flag is not set for characteristic" << charHandle;
1710 auto characteristicCallback = [charHandle, service, newValue, writeWithResponse,
this](
1711 GattCharacteristic characteristic) {
1712 writeCharacteristicHelper(service, charHandle, newValue, writeWithResponse,
1716 if (!getNativeCharacteristic(service->uuid, charData.uuid, characteristicCallback)) {
1717 qCDebug(QT_BT_WINDOWS) <<
"Could not obtain native characteristic" << charData.uuid
1718 <<
"from service" << service->uuid;
1719 service->setError(QLowEnergyService::CharacteristicWriteError);
1723void QLowEnergyControllerPrivateWinRT::writeCharacteristicHelper(
1724 const QSharedPointer<QLowEnergyServicePrivate> service,
1725 const QLowEnergyHandle charHandle,
const QByteArray &newValue,
1726 bool writeWithResponse, GattCharacteristic characteristic)
1728 const quint32 length = quint32(newValue.length());
1729 Buffer buffer =
nullptr;
1730 if (!
TRY(buffer = Buffer(length)))
1731 RETURN_SERVICE_ERROR(
"Could not create buffer", service, QLowEnergyService::CharacteristicWriteError);
1734 if (!
TRY(bytes = buffer.data()))
1735 RETURN_SERVICE_ERROR(
"Could not set buffer", service, QLowEnergyService::CharacteristicWriteError);
1737 memcpy(bytes, newValue, length);
1738 if (!
TRY(buffer.Length(length)))
1739 RETURN_SERVICE_ERROR(
"Could not set buffer length", service, QLowEnergyService::CharacteristicWriteError);
1741 GattWriteOption option = writeWithResponse ? GattWriteOption::WriteWithResponse
1742 : GattWriteOption::WriteWithoutResponse;
1743 auto writeOp =
SAFE(characteristic.WriteValueAsync(buffer, option));
1745 RETURN_SERVICE_ERROR(
"Could not write characteristic", service, QLowEnergyService::CharacteristicWriteError);
1747 const auto charData = service->characteristicList.value(charHandle);
1748 QPointer<QLowEnergyControllerPrivateWinRT> thisPtr(
this);
1749 auto writeCompletedLambda =
1750 [charData, charHandle, newValue, service, writeWithResponse, thisPtr]
1751 (IAsyncOperation<GattCommunicationStatus>
const &op, winrt::AsyncStatus
const status)
1753 if (status == winrt::AsyncStatus::Canceled || status == winrt::AsyncStatus::Error) {
1754 qCDebug(QT_BT_WINDOWS) <<
"Characteristic" << charHandle
1755 <<
"write operation failed (async status)";
1756 service->setError(QLowEnergyService::CharacteristicWriteError);
1760 GattCommunicationStatus result;
1761 auto hr =
HR(result = op.GetResults());
1762 if (hr == E_BLUETOOTH_ATT_INVALID_ATTRIBUTE_VALUE_LENGTH) {
1763 qCDebug(QT_BT_WINDOWS) <<
"Characteristic" << charHandle
1764 <<
"write operation was tried with invalid value length";
1765 service->setError(QLowEnergyService::CharacteristicWriteError);
1767 }
else if (FAILED(hr)) {
1768 RETURN_SERVICE_ERROR(
"Could not obtain characteristic write result", service, QLowEnergyService::CharacteristicWriteError);
1771 if (result != GattCommunicationStatus::Success) {
1772 qCDebug(QT_BT_WINDOWS) <<
"Characteristic" << charHandle
1773 <<
"write operation failed (communication status)";
1774 service->setError(QLowEnergyService::CharacteristicWriteError);
1779 if (thisPtr && charData.properties & QLowEnergyCharacteristic::Read)
1780 thisPtr->updateValueOfCharacteristic(charHandle, newValue,
false);
1781 if (writeWithResponse) {
1782 emit service->characteristicWritten(QLowEnergyCharacteristic(service, charHandle),
1787 if (!
TRY(writeOp.Completed(writeCompletedLambda)))
1788 RETURN_SERVICE_ERROR(
"Could not register characteristic write callback", service, QLowEnergyService::CharacteristicWriteError);
1792 const QSharedPointer<QLowEnergyServicePrivate> service,
1793 const QLowEnergyHandle charHandle,
1794 const QLowEnergyHandle descHandle,
1795 const QByteArray &newValue)
1797 qCDebug(QT_BT_WINDOWS) <<
__FUNCTION__ << service << charHandle << descHandle << newValue;
1798 qCDebug(QT_BT_WINDOWS_SERVICE_THREAD) <<
__FUNCTION__ <<
"Changing service pointer from thread"
1799 << QThread::currentThread();
1800 Q_ASSERT(!service.isNull());
1801 if (role == QLowEnergyController::PeripheralRole) {
1802 service->setError(QLowEnergyService::DescriptorWriteError);
1807 if (!service->characteristicList.contains(charHandle)) {
1808 qCDebug(QT_BT_WINDOWS) <<
"Descriptor" << descHandle <<
"in characteristic" << charHandle
1809 <<
"could not be found in service" << service->uuid;
1810 service->setError(QLowEnergyService::DescriptorWriteError);
1814 const auto charData = service->characteristicList.value(charHandle);
1816 auto characteristicCallback = [descHandle, charHandle, service, newValue,
this](
1817 GattCharacteristic characteristic) {
1818 writeDescriptorHelper(service, charHandle, descHandle, newValue, characteristic);
1821 if (!getNativeCharacteristic(service->uuid, charData.uuid, characteristicCallback)) {
1822 qCDebug(QT_BT_WINDOWS) <<
"Could not obtain native characteristic" << charData.uuid
1823 <<
"from service" << service->uuid;
1824 service->setError(QLowEnergyService::DescriptorWriteError);
1828void QLowEnergyControllerPrivateWinRT::writeDescriptorHelper(
1829 const QSharedPointer<QLowEnergyServicePrivate> service,
1830 const QLowEnergyHandle charHandle,
1831 const QLowEnergyHandle descHandle,
1832 const QByteArray &newValue,
1833 GattCharacteristic characteristic)
1836 const auto charData = service->characteristicList.value(charHandle);
1837 if (!charData.descriptorList.contains(descHandle)) {
1838 qCDebug(QT_BT_WINDOWS) <<
"Descriptor" << descHandle
1839 <<
"could not be found in Characteristic" << charHandle;
1843 if (descData.uuid ==
1844 QBluetoothUuid(QBluetoothUuid::DescriptorType::ClientCharacteristicConfiguration)) {
1845 GattClientCharacteristicConfigurationDescriptorValue value;
1846 quint16 intValue = qFromLittleEndian<quint16>(newValue);
1847 if ((intValue & GattClientCharacteristicConfigurationDescriptorValue::Indicate)
1848 && (intValue & GattClientCharacteristicConfigurationDescriptorValue::Notify)) {
1849 qCWarning(QT_BT_WINDOWS) <<
"Setting both Indicate and Notify "
1850 "is not supported on WinRT";
1851 value = GattClientCharacteristicConfigurationDescriptorValue(
1852 (GattClientCharacteristicConfigurationDescriptorValue::Indicate
1853 | GattClientCharacteristicConfigurationDescriptorValue::Notify));
1854 }
else if (intValue & GattClientCharacteristicConfigurationDescriptorValue::Indicate) {
1855 value = GattClientCharacteristicConfigurationDescriptorValue::Indicate;
1856 }
else if (intValue & GattClientCharacteristicConfigurationDescriptorValue::Notify) {
1857 value = GattClientCharacteristicConfigurationDescriptorValue::Notify;
1858 }
else if (intValue == 0) {
1859 value = GattClientCharacteristicConfigurationDescriptorValue::None;
1861 qCDebug(QT_BT_WINDOWS) <<
"Descriptor" << descHandle
1862 <<
"write operation failed: Invalid value";
1863 service->setError(QLowEnergyService::DescriptorWriteError);
1867 auto writeOp =
SAFE(characteristic.WriteClientCharacteristicConfigurationDescriptorAsync(value));
1869 RETURN_SERVICE_ERROR(
"Could not write client characteristic configuration", service, QLowEnergyService::DescriptorWriteError);
1871 QPointer<QLowEnergyControllerPrivateWinRT> thisPtr(
this);
1872 auto writeCompletedLambda = [charHandle, descHandle, newValue, service, thisPtr]
1873 (IAsyncOperation<GattCommunicationStatus>
const &op, winrt::AsyncStatus
const status)
1875 if (status == winrt::AsyncStatus::Canceled || status == winrt::AsyncStatus::Error) {
1876 qCDebug(QT_BT_WINDOWS) <<
"Descriptor" << descHandle <<
"write operation failed";
1877 service->setError(QLowEnergyService::DescriptorWriteError);
1881 GattCommunicationStatus result;
1882 if (!
TRY(result = op.GetResults()))
1883 RETURN_SERVICE_ERROR(
"Could not obtain result for descriptor", service, QLowEnergyService::DescriptorWriteError);
1885 if (result != GattCommunicationStatus::Success) {
1886 qCWarning(QT_BT_WINDOWS) <<
"Descriptor" << descHandle <<
"write operation failed";
1887 service->setError(QLowEnergyService::DescriptorWriteError);
1891 thisPtr->updateValueOfDescriptor(charHandle, descHandle, newValue,
false);
1892 emit service->descriptorWritten(QLowEnergyDescriptor(service, charHandle, descHandle),
1896 if (!
TRY(writeOp.Completed(writeCompletedLambda)))
1897 RETURN_SERVICE_ERROR(
"Could not register descriptor write callback", service, QLowEnergyService::DescriptorWriteError);
1902 auto result =
SAFE(await(characteristic.GetDescriptorsForUuidAsync(GUID(descData.uuid))));
1904 RETURN_SERVICE_ERROR(
"Could not obtain descriptor from Uuid", service, QLowEnergyService::DescriptorWriteError);
1906 GattCommunicationStatus commStatus;
1907 if (!
TRY(commStatus = result.Status()) || commStatus != GattCommunicationStatus::Success) {
1908 qCWarning(QT_BT_WINDOWS) <<
"Descriptor operation failed";
1909 service->setError(QLowEnergyService::DescriptorWriteError);
1913 auto descriptors =
SAFE(result.Descriptors());
1915 RETURN_SERVICE_ERROR(
"Could not obtain list of descriptors", service, QLowEnergyService::DescriptorWriteError);
1918 if (!
TRY(size = descriptors.Size()))
1919 RETURN_SERVICE_ERROR(
"Could not obtain list of descriptors' size", service, QLowEnergyService::DescriptorWriteError);
1922 qCWarning(QT_BT_WINDOWS) <<
"No descriptor with uuid" << descData.uuid <<
"was found.";
1924 }
else if (size > 1) {
1925 qCWarning(QT_BT_WINDOWS) <<
"There is more than 1 descriptor with uuid" << descData.uuid;
1928 auto descriptor =
SAFE(descriptors.GetAt(0));
1930 RETURN_SERVICE_ERROR(
"Could not obtain descriptor", service, QLowEnergyService::DescriptorWriteError);
1932 const quint32 length = quint32(newValue.length());
1933 Buffer buffer =
nullptr;
1934 if (!
TRY(buffer = Buffer(length)))
1935 RETURN_SERVICE_ERROR(
"Could not create buffer", service, QLowEnergyService::CharacteristicWriteError);
1938 if (!
TRY(bytes = buffer.data()))
1939 RETURN_SERVICE_ERROR(
"Could not set buffer", service, QLowEnergyService::CharacteristicWriteError);
1941 memcpy(bytes, newValue, length);
1942 if (!
TRY(buffer.Length(length)))
1943 RETURN_SERVICE_ERROR(
"Could not set buffer length", service, QLowEnergyService::CharacteristicWriteError);
1945 auto writeOp =
SAFE(descriptor.WriteValueAsync(buffer));
1947 RETURN_SERVICE_ERROR(
"Could not write descriptor value", service, QLowEnergyService::CharacteristicWriteError);
1949 QPointer<QLowEnergyControllerPrivateWinRT> thisPtr(
this);
1950 auto writeCompletedLambda = [charHandle, descHandle, newValue, service, thisPtr]
1951 (IAsyncOperation<GattCommunicationStatus>
const &op, winrt::AsyncStatus
const status)
1953 if (status == winrt::AsyncStatus::Canceled || status == winrt::AsyncStatus::Error) {
1954 qCDebug(QT_BT_WINDOWS) <<
"Descriptor" << descHandle <<
"write operation failed";
1955 service->setError(QLowEnergyService::DescriptorWriteError);
1959 GattCommunicationStatus result;
1960 if (!
TRY(result = op.GetResults()))
1961 RETURN_SERVICE_ERROR(
"Could not obtain result for descriptor", service, QLowEnergyService::DescriptorWriteError);
1963 if (result != GattCommunicationStatus::Success) {
1964 qCDebug(QT_BT_WINDOWS) <<
"Descriptor" << descHandle <<
"write operation failed";
1965 service->setError(QLowEnergyService::DescriptorWriteError);
1969 thisPtr->updateValueOfDescriptor(charHandle, descHandle, newValue,
false);
1970 emit service->descriptorWritten(QLowEnergyDescriptor(service, charHandle, descHandle),
1974 if (!
TRY(writeOp.Completed(writeCompletedLambda)))
1975 RETURN_SERVICE_ERROR(
"Could not register descriptor write callback", service, QLowEnergyService::DescriptorWriteError);
1985int QLowEnergyControllerPrivateWinRT::
mtu()
const
1988 if (!mGattSession) {
1989 qCDebug(QT_BT_WINDOWS) <<
"mtu queried before GattSession available. Using default mtu.";
1993 if (!
TRY(mtu = mGattSession.MaxPduSize()))
1996 qCDebug(QT_BT_WINDOWS) <<
"mtu determined to be" << mtu;
2000void QLowEnergyControllerPrivateWinRT::handleCharacteristicChanged(
2001 quint16 charHandle,
const QByteArray &data)
2003 qCDebug(QT_BT_WINDOWS) <<
__FUNCTION__ << charHandle << data;
2004 qCDebug(QT_BT_WINDOWS_SERVICE_THREAD) <<
__FUNCTION__ <<
"Changing service pointer from thread"
2005 << QThread::currentThread();
2006 QSharedPointer<QLowEnergyServicePrivate> service =
2007 serviceForHandle(charHandle);
2008 if (service.isNull())
2011 qCDebug(QT_BT_WINDOWS) <<
"Characteristic change notification" << service->uuid
2012 << charHandle << data.toHex();
2014 QLowEnergyCharacteristic characteristic = characteristicForHandle(charHandle);
2015 if (!characteristic.isValid()) {
2016 qCWarning(QT_BT_WINDOWS) <<
"characteristicChanged: Cannot find characteristic";
2022 if (characteristic.properties() & QLowEnergyCharacteristic::Read)
2023 updateValueOfCharacteristic(characteristic.attributeHandle(),
2025 emit service->characteristicChanged(characteristic, data);
2028void QLowEnergyControllerPrivateWinRT::handleServiceHandlerError(
const QString &error)
2030 if (state != QLowEnergyController::DiscoveringState)
2033 qCWarning(QT_BT_WINDOWS) <<
"Error while discovering services:" << error;
2034 setState(QLowEnergyController::UnconnectedState);
2035 setError(QLowEnergyController::ConnectionError);
2038void QLowEnergyControllerPrivateWinRT::handleConnectionError(
const char *logMessage)
2040 qCWarning(QT_BT_WINDOWS) << logMessage;
2041 setError(QLowEnergyController::ConnectionError);
2042 setState(QLowEnergyController::UnconnectedState);
2043 unregisterFromStatusChanges();
2044 unregisterFromMtuChanges();
2049#include "qlowenergycontroller_winrt.moc"
void discoverServiceDetails(const QBluetoothUuid &service, QLowEnergyService::DiscoveryMode mode) override
void stopAdvertising() override
~QLowEnergyControllerPrivateWinRT() override
void addToGenericAttributeList(const QLowEnergyServiceData &service, QLowEnergyHandle startHandle) override
void readDescriptor(const QSharedPointer< QLowEnergyServicePrivate > service, const QLowEnergyHandle charHandle, const QLowEnergyHandle descriptorHandle) override
void connectToDevice() override
void disconnectFromDevice() override
void writeDescriptor(const QSharedPointer< QLowEnergyServicePrivate > service, const QLowEnergyHandle charHandle, const QLowEnergyHandle descriptorHandle, const QByteArray &newValue) override
void startAdvertising(const QLowEnergyAdvertisingParameters ¶ms, const QLowEnergyAdvertisingData &advertisingData, const QLowEnergyAdvertisingData &scanResponseData) override
void readCharacteristic(const QSharedPointer< QLowEnergyServicePrivate > service, const QLowEnergyHandle charHandle) override
void writeCharacteristic(const QSharedPointer< QLowEnergyServicePrivate > service, const QLowEnergyHandle charHandle, const QByteArray &newValue, QLowEnergyService::WriteMode mode) override
void requestConnectionUpdate(const QLowEnergyConnectionParameters ¶ms) override
void discoverServices() override
void invalidateServices()
void setController(QLowEnergyControllerPrivate *control)
void errorOccurred(const QString &error)
void handleDeviceDisconnectRequest()
uint mCharacteristicsCountToBeDiscovered
QHash< QLowEnergyHandle, QLowEnergyServicePrivate::CharData > mCharacteristicList
void errorOccured(const QString &error)
QLowEnergyService::DiscoveryMode mMode
GattDeviceService mDeviceService
QList< QBluetoothUuid > mIndicateChars
void registerQLowEnergyControllerMetaType()
#define RETURN_FALSE(msg)
#define DEC_CHAR_COUNT_AND_CONTINUE(msg)
constexpr T & bitwise_or_equal(T &a, const E &b)
#define ENUM_BITWISE_OPS(E)
QT_BEGIN_NAMESPACE typedef GattReadClientCharacteristicConfigurationDescriptorResult ClientCharConfigDescriptorResult
static T await_forever(IAsyncOperation< T > asyncInfo, GlobalCondition canceled=never)
static QByteArray byteArrayFromGattResult(GattReadResult gattResult, bool isWCharString=false)
constexpr std::underlying_type_t< E > bitwise_or(E x, E y)
constexpr T bitwise_or(T x, E y)
std::function< bool()> GlobalCondition
static T await(IAsyncOperation< T > asyncInfo, GlobalCondition canceled=never, int timeout=5000)
static QByteArray byteArrayFromBuffer(IBuffer buffer, bool isWCharString=false)
#define RETURN_SERVICE_ERROR(msg, service, error)
constexpr std::underlying_type_t< E > bitwise_and(E x, E y)
static constexpr bool never()
constexpr T bitwise_and(T x, E y)
constexpr int timeout_infinity
#define WARN_AND_CONTINUE(msg)