Qt
Internal/Contributor docs for the Qt SDK. Note: These are NOT official API docs; those are found at https://doc.qt.io/
Loading...
Searching...
No Matches
qlowenergycontroller_winrt.cpp
Go to the documentation of this file.
1// Copyright (C) 2021 The Qt Company Ltd.
2// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
3
6
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>
12
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>
20
21#include <functional>
22#include <type_traits>
23
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>
31
32#include <windows.devices.bluetooth.h>
33#include <windows.devices.bluetooth.genericattributeprofile.h>
34
35using namespace winrt;
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;
43
49
50template<typename E,
51 std::enable_if_t<std::is_enum_v<E>, int> = 0>
52inline constexpr std::underlying_type_t<E> bitwise_and(E x, E y)
53{
54 return static_cast<std::underlying_type_t<E>>(x) & static_cast<std::underlying_type_t<E>>(y);
55}
56
57template<typename T, typename E,
58 std::enable_if_t<std::conjunction_v<std::is_integral<T>, std::is_enum<E>>, int> = 0>
59inline constexpr T bitwise_and(T x, E y)
60{
61 return x & static_cast<std::underlying_type_t<E>>(y);
62}
63
64template<typename E,
65 std::enable_if_t<std::is_enum_v<E>, int> = 0>
66inline constexpr std::underlying_type_t<E> bitwise_or(E x, E y)
67{
68 return static_cast<std::underlying_type_t<E>>(x) | static_cast<std::underlying_type_t<E>>(y);
69}
70
71template<typename T, typename E,
72 std::enable_if_t<std::conjunction_v<std::is_integral<T>, std::is_enum<E>>, int> = 0>
73inline constexpr T bitwise_or(T x, E y)
74{
75 return x | static_cast<std::underlying_type_t<E>>(y);
76}
77
78template<typename T, typename E,
79 std::enable_if_t<std::conjunction_v<std::is_integral<T>, std::is_enum<E>>, int> = 0>
80inline constexpr T &bitwise_or_equal(T &a, const E &b)
81{
82 a |= static_cast<std::underlying_type_t<E>>(b);
83 return a;
84}
85
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
88
89 <typename T> inline
90 constexpr T operator&(T x, E y) { return bitwise_and<T, E>(x, y); } template
91
92 <typename T> inline
93 constexpr T operator&(E x, T y) { return bitwise_and<T, E>(y, x); } inline
94
95 constexpr std::underlying_type_t<E> operator|(E x, E y) { return bitwise_or<E>(x, y); } template
96
97 <typename T> inline
98 constexpr T operator|(T x, E y) { return bitwise_or<T, E>(x, y); } template
99
100 <typename T> inline
101 constexpr T operator|(E x, T y) { return bitwise_or<T, E>(y, x); } template
102
103 <typename T> inline
104 constexpr T &operator |=(T &a, const E &b) { return bitwise_or_equal(a, b); }
105
106QT_BEGIN_NAMESPACE
107
108ENUM_BITWISE_OPS(GattClientCharacteristicConfigurationDescriptorValue)
109
111
112using GlobalCondition = std::function<bool()>;
113static constexpr bool never() { return false; }
114
115template <typename T>
116static T await(IAsyncOperation<T> asyncInfo, GlobalCondition canceled = never, int timeout = 5000)
117{
118 QDeadlineTimer awaitTime(timeout);
119 do {
120 QThread::yieldCurrentThread();
121 if (asyncInfo.Status() != winrt::AsyncStatus::Started) {
122 check_hresult(asyncInfo.ErrorCode());
123 return asyncInfo.GetResults();
124 }
125 QCoreApplication::processEvents(QEventLoop::AllEvents);
126 } while (!canceled() && !awaitTime.hasExpired());
127 asyncInfo.Cancel();
128 throw hresult_error(E_ABORT);
129}
130
131constexpr int timeout_infinity = -1;
132
133template <typename T>
134static inline T await_forever(IAsyncOperation<T> asyncInfo, GlobalCondition canceled = never)
135{
136 return await(asyncInfo, canceled, timeout_infinity);
137}
138
139#define WARN_AND_CONTINUE(msg)
140 {
141 qCWarning(QT_BT_WINDOWS) << msg;
142 continue;
143 }
144
145#define DEC_CHAR_COUNT_AND_CONTINUE(msg)
146 {
147 qCWarning(QT_BT_WINDOWS) << msg;
148 --mCharacteristicsCountToBeDiscovered;
149 continue;
150 }
151
152#define RETURN_SERVICE_ERROR(msg, service, error)
153 {
154 qCDebug(QT_BT_WINDOWS) << msg;
155 service->setError(error);
156 return;
157 }
158
159#define RETURN_FALSE(msg)
160 {
161 qErrnoWarning(msg);
162 return false;
163 }
164
165#define RETURN_MSG(msg)
166 {
167 qErrnoWarning(msg);
168 return;
169 }
170
171Q_DECLARE_LOGGING_CATEGORY(QT_BT_WINDOWS)
172Q_DECLARE_LOGGING_CATEGORY(QT_BT_WINDOWS_SERVICE_THREAD)
173
174static constexpr qint64 kMaxConnectTimeout = 20000; // 20 sec
175
176static QByteArray byteArrayFromBuffer(IBuffer buffer, bool isWCharString = false)
177{
178 if (!buffer) {
179 qErrnoWarning("nullptr passed to byteArrayFromBuffer");
180 return QByteArray();
181 }
182 qsizetype size = SAFE(buffer.Length());
183 if (!size)
184 return QByteArray();
185 if (isWCharString) {
186 QString valueString = QString::fromUtf16(
187 reinterpret_cast<char16_t *>(buffer.data())).left(size / 2);
188 return valueString.toUtf8();
189 }
190 return QByteArray(reinterpret_cast<char *>(buffer.data()), size);
191}
192
193static QByteArray byteArrayFromGattResult(GattReadResult gattResult,
194 bool isWCharString = false)
195{
196 auto buffer = SAFE(gattResult.Value());
197 if (!buffer) {
198 qCWarning(QT_BT_WINDOWS) << "Could not obtain buffer from GattReadResult";
199 return QByteArray();
200 }
201 return byteArrayFromBuffer(buffer, isWCharString);
202}
203
205{
207public:
215
222
223public slots:
225 {
226 auto exitCondition = [this]() { return mAbortRequested; };
227
229 qCDebug(QT_BT_WINDOWS) << __FUNCTION__;
230
234 return emitErrorAndQuitThread(QLatin1String("Could not obtain char list"));
235
237 return emitErrorAndQuitThread(QLatin1String("Could not obtain char list"));
238
240 if (!characteristics)
241 return emitErrorAndQuitThread(QLatin1String("Could not obtain char list"));
242
245 return emitErrorAndQuitThread(QLatin1String("Could not obtain char list"));
246
248 for (uint i = 0; !mAbortRequested && (i < characteristicsCount); ++i) {
250 if (!characteristic) {
251 qCWarning(QT_BT_WINDOWS) << "Could not obtain characteristic at" << i;
253 continue;
254 }
255
256 // For some strange reason, Windows doesn't discover descriptors of characteristics (if not paired).
257 // Qt API assumes that all characteristics and their descriptors are discovered in one go.
258 // So we start 'GetDescriptorsAsync' for each discovered characteristic and finish only
259 // when GetDescriptorsAsync for all characteristics return.
261 if (!descResult)
262 DEC_CHAR_COUNT_AND_CONTINUE("Could not obtain descriptor read result");
263
264 uint16_t handle = 0;
266 DEC_CHAR_COUNT_AND_CONTINUE("Could not obtain characteristic's attribute handle");
267
270 if (mStartHandle == 0 || mStartHandle > handle)
272 if (mEndHandle == 0 || mEndHandle < handle)
274
276 DEC_CHAR_COUNT_AND_CONTINUE("Could not read characteristic UUID");
277
280 DEC_CHAR_COUNT_AND_CONTINUE("Could not read characteristic properties");
281
285
286 GattReadResult readResult = nullptr;
288 DEC_CHAR_COUNT_AND_CONTINUE("Could not read characteristic");
289
290 if (!readResult)
291 qCWarning(QT_BT_WINDOWS) << "Characteristic read result is null";
292 else
294 }
295 // Insert the characteristic before its descriptors are discovered. Descriptor
296 // discovery below can fail, but the characteristic itself was discovered and
297 // has to stay visible in the Qt API. All further updates go through charIt,
298 // which stays valid until the next insertion into mCharacteristicList, i.e.
299 // until the next iteration of this loop.
301
303 DEC_CHAR_COUNT_AND_CONTINUE("Descriptor operation failed");
304
306 if (!descriptors)
307 DEC_CHAR_COUNT_AND_CONTINUE("Could not obtain list of descriptors");
310 DEC_CHAR_COUNT_AND_CONTINUE("Could not obtain list of descriptors' size");
311 for (uint j = 0; !mAbortRequested && (j < descriptorCount); ++j) {
314 if (!descriptor)
315 WARN_AND_CONTINUE("Could not access descriptor");
318 WARN_AND_CONTINUE("Could not get descriptor handle");
320 WARN_AND_CONTINUE("Could not get descriptor UUID");
321 // Same reasoning as for the characteristic above: reading the value can
322 // fail, but the descriptor was discovered and has to be reported. descIt
323 // stays valid until the next insertion into the descriptor list, i.e.
324 // until the next iteration of this loop.
330 if (!readResult)
331 WARN_AND_CONTINUE("Could not read descriptor value");
334 WARN_AND_CONTINUE("Could not get descriptor value from result");
335 quint16 result = 0;
336 bool correct = false;
339 correct = true;
340 }
343 correct = true;
344 }
346 correct = true;
347 if (!correct)
348 continue;
349
352 }
353 } else {
355
357 if (!readResult)
358 WARN_AND_CONTINUE("Could not read descriptor value");
360 }
361 }
362 }
363
365 }
367 }
368
370 {
371 mAbortRequested = true;
372 }
373
374private:
376 void emitErrorAndQuitThread(const QString &error);
377
378public:
387 bool mAbortRequested = false;
388
389signals:
394 void errorOccured(const QString &error);
395};
396
397void QWinRTLowEnergyServiceHandler::checkAllCharacteristicsDiscovered()
398{
399 if (!mAbortRequested && (mCharacteristicsCountToBeDiscovered == 0)) {
400 emit charListObtained(mService, mCharacteristicList, mIndicateChars,
401 mStartHandle, mEndHandle);
402 }
403 QThread::currentThread()->quit();
404}
405
406void QWinRTLowEnergyServiceHandler::emitErrorAndQuitThread(const QString &error)
407{
408 mAbortRequested = true; // so that the service is closed during cleanup
409 emit errorOccured(error);
410 QThread::currentThread()->quit();
411}
412
414{
416public:
418 {
419 qCDebug(QT_BT_WINDOWS) << __FUNCTION__;
420 // This should be checked before the handler is created
422 }
424 {
425 qCDebug(QT_BT_WINDOWS) << __FUNCTION__;
426 mDevice = nullptr;
427 mGattSession = nullptr;
428 // To close the COM library gracefully, each successful call to
429 // CoInitialize, including those that return S_FALSE, must be balanced
430 // by a corresponding call to CoUninitialize.
431 if (mComInitialized)
433 }
434
435public slots:
438
439signals:
441 void errorOccurred(const QString &error);
442
443private:
444 void connectToPairedDevice();
445 void connectToUnpairedDevice();
446 void emitErrorAndQuitThread(const QString &error);
447 void emitErrorAndQuitThread(const char *error);
448 void emitConnectedAndQuitThread();
449
450 BluetoothLEDevice mDevice = nullptr;
451 GattSession mGattSession = nullptr;
452 const QBluetoothAddress mAddress;
453 bool mAbortConnection = false;
454 bool mComInitialized = false;
455};
456
457void QWinRTLowEnergyConnectionHandler::connectToDevice()
458{
459 qCDebug(QT_BT_WINDOWS) << __FUNCTION__;
460 mComInitialized = TRY(winrt::init_apartment());
461
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");
465
466 // get GattSession: 1. get device id
467 BluetoothDeviceId deviceId = SAFE(mDevice.BluetoothDeviceId());
468 if (!deviceId)
469 return emitErrorAndQuitThread("Could not get device id");
470
471 // get GattSession: 3. get session
472 if (!(mGattSession = SAFE(await(GattSession::FromDeviceIdAsync(deviceId), earlyExit))))
473 return emitErrorAndQuitThread("Could not get GattSession from id");
474
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();
480
481 QBluetoothLocalDevice localDevice;
482 QBluetoothLocalDevice::Pairing pairing = localDevice.pairingStatus(mAddress);
483 if (pairing == QBluetoothLocalDevice::Unpaired)
484 connectToUnpairedDevice();
485 else
486 connectToPairedDevice();
487}
488
490{
491 mAbortConnection = true;
492 // Disconnect from the QLowEnergyControllerPrivateWinRT, so that it does
493 // not get notifications. It's absolutely fine to keep doing smth in
494 // background, as multiple connections to the same device should be handled
495 // correctly by OS.
496 disconnect(this, &QWinRTLowEnergyConnectionHandler::deviceConnected, nullptr, nullptr);
497 disconnect(this, &QWinRTLowEnergyConnectionHandler::errorOccurred, nullptr, nullptr);
498}
499
500void QWinRTLowEnergyConnectionHandler::connectToPairedDevice()
501{
502 auto earlyExit = [this]() { return mAbortConnection; };
503 QDeadlineTimer deadline(kMaxConnectTimeout);
504 while (!mAbortConnection && !deadline.hasExpired()) {
505
506 auto deviceServicesResult = SAFE(await(mDevice.GetGattServicesAsync(), earlyExit));
507 if (!deviceServicesResult)
508 return emitErrorAndQuitThread("Could not obtain services");
509
510 if (!SAFE(deviceServicesResult.Status() == GattCommunicationStatus::Success))
511 return emitErrorAndQuitThread("Service operation failed");
512
513 auto deviceServices = SAFE(deviceServicesResult.Services());
514 if (!deviceServices)
515 return emitErrorAndQuitThread("Could not obtain list of services");
516
517 uint serviceCount;
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");
522
523 // Windows automatically connects to the device as soon as a service value is read/written.
524 // Thus we read one value in order to establish the connection.
525 for (uint i = 0; i < serviceCount; ++i) {
526
527 auto service = SAFE(deviceServices.GetAt(i));
528 if (!service)
529 return emitErrorAndQuitThread("Could not obtain service");
530
531 auto characteristicsResult = SAFE(await(service.GetCharacteristicsAsync(), earlyExit));
532 if (!characteristicsResult)
533 return emitErrorAndQuitThread("Could not obtain characteristic");
534
535 if (!SAFE(characteristicsResult.Status() == GattCommunicationStatus::Success)) {
536 qCWarning(QT_BT_WINDOWS) << "Characteristic operation failed";
537 break;
538 }
539
540 IVectorView<GattCharacteristic> characteristics = nullptr;
541 auto hr = HR(characteristics = characteristicsResult.Characteristics());
542 if (hr == E_ACCESSDENIED) {
543 // Everything will work as expected up until this point if the
544 // manifest capabilties for bluetooth LE are not set.
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.");
549 }
550
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) {
555
556 auto characteristic = SAFE(characteristics.GetAt(j));
557 if (!characteristic)
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) {
563 // E_ILLEGAL_METHOD_CALL will be the result for a device, that is not reachable at
564 // the moment. In this case we should jump back into the outer loop and keep trying.
565 break;
566 } else if (FAILED(hr) || !result) {
567 return emitErrorAndQuitThread("Could not read characteristic value");
568 }
569
570 auto buffer = SAFE(result.Value());
571 if (!buffer) {
572 qCDebug(QT_BT_WINDOWS) << "Problem reading value";
573 break;
574 }
575
576 emitConnectedAndQuitThread();
577 return;
578 }
579 }
580 }
581 // If we got here because of mAbortConnection == true, the error message
582 // will not be delivered, so it does not matter. But we need to terminate
583 // the thread anyway!
584 emitErrorAndQuitThread("Connect to device failed due to timeout!");
585}
586
587void QWinRTLowEnergyConnectionHandler::connectToUnpairedDevice()
588{
589 qCDebug(QT_BT_WINDOWS) << __FUNCTION__;
590
591 auto earlyExit = [this]() { return mAbortConnection; };
592 QDeadlineTimer deadline(kMaxConnectTimeout);
593 while (!mAbortConnection && !deadline.hasExpired()) {
594
595 auto deviceServicesResult = SAFE(await_forever(mDevice.GetGattServicesAsync(), earlyExit));
596 if (!deviceServicesResult)
597 return emitErrorAndQuitThread("Could not obtain services");
598
599 GattCommunicationStatus commStatus;
600 if (!TRY(commStatus = deviceServicesResult.Status()))
601 return emitErrorAndQuitThread("Could not obtain comm status");
602 if (commStatus == GattCommunicationStatus::Unreachable)
603 continue;
604 if (commStatus != GattCommunicationStatus::Success)
605 return emitErrorAndQuitThread("Service operation failed");
606
607 emitConnectedAndQuitThread();
608 return;
609 }
610 // If we got here because of mAbortConnection == true, the error message
611 // will not be delivered, so it does not matter. But we need to terminate
612 // the thread anyway!
613 emitErrorAndQuitThread("Connect to device failed due to timeout!");
614}
615
616void QWinRTLowEnergyConnectionHandler::emitErrorAndQuitThread(const QString &error)
617{
618 emit errorOccurred(error);
619 QThread::currentThread()->quit();
620}
621
622void QWinRTLowEnergyConnectionHandler::emitErrorAndQuitThread(const char *error)
623{
624 emitErrorAndQuitThread(QString::fromUtf8(error));
625}
626
627void QWinRTLowEnergyConnectionHandler::emitConnectedAndQuitThread()
628{
629 emit deviceConnected(mDevice.as<abi::BluetoothLEDevice>(), mGattSession.as<abi::GattSession>());
630 QThread::currentThread()->quit();
631}
632
633QLowEnergyControllerPrivateWinRT::QLowEnergyControllerPrivateWinRT()
635{
637 connect(this, &QLowEnergyControllerPrivateWinRT::characteristicChanged,
638 this, &QLowEnergyControllerPrivateWinRT::handleCharacteristicChanged,
639 Qt::QueuedConnection);
640}
641
642QLowEnergyControllerPrivateWinRT::~QLowEnergyControllerPrivateWinRT()
643{
644 unregisterFromStatusChanges();
645 unregisterFromValueChanges();
646}
647
648void QLowEnergyControllerPrivateWinRT::init()
649{
650}
651
652void QLowEnergyControllerPrivateWinRT::connectToDevice()
653{
654 qCDebug(QT_BT_WINDOWS) << __FUNCTION__;
655 if (remoteDevice.isNull()) {
656 qCWarning(QT_BT_WINDOWS) << "Invalid/null remote device address";
657 setError(QLowEnergyController::UnknownRemoteDeviceError);
658 return;
659 }
660 setState(QLowEnergyController::ConnectingState);
661
662 QWinRTLowEnergyConnectionHandler *worker = new QWinRTLowEnergyConnectionHandler(remoteDevice);
663 QThread *thread = new QThread;
664 worker->moveToThread(thread);
665 connect(this, &QLowEnergyControllerPrivateWinRT::abortConnection, worker,
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");
676 return;
677 }
678 mDevice = device.as<BluetoothLEDevice>();
679 mGattSession = session.as<GattSession>();
680
681 if (!registerForStatusChanges() || !registerForMtuChanges()) {
682 handleConnectionError("Failed to register for changes");
683 return;
684 }
685
686 Q_Q(QLowEnergyController);
687 setState(QLowEnergyController::ConnectedState);
688 emit q->connected();
689 });
690 thread->start();
691}
692
693void QLowEnergyControllerPrivateWinRT::disconnectFromDevice()
694{
695 qCDebug(QT_BT_WINDOWS) << __FUNCTION__;
696 Q_Q(QLowEnergyController);
697 setState(QLowEnergyController::ClosingState);
698 emit abortConnection();
699 unregisterFromValueChanges();
700 unregisterFromStatusChanges();
701 unregisterFromMtuChanges();
702 clearAllServices();
703 mGattSession = nullptr;
704 mDevice = nullptr;
705 setState(QLowEnergyController::UnconnectedState);
706 emit q->disconnected();
707}
708
709bool QLowEnergyControllerPrivateWinRT::getNativeService(const QBluetoothUuid &serviceUuid,
710 NativeServiceCallback callback)
711{
712 if (m_openedServices.contains(serviceUuid)) {
713 callback(m_openedServices.value(serviceUuid, nullptr));
714 return true;
715 }
716
717 auto servicesResultOperation = SAFE(mDevice.GetGattServicesForUuidAsync(GUID(serviceUuid)));
718 if (!servicesResultOperation)
719 RETURN_FALSE("Could not start async services request");
720
721 QPointer<QLowEnergyControllerPrivateWinRT> thisPtr(this);
722 bool ok = TRY(servicesResultOperation.Completed(
723 [thisPtr, callback, serviceUuid](
724 IAsyncOperation<GattDeviceServicesResult> const &op, winrt::AsyncStatus const status)
725 {
726 // returns the service or nullptr in case of an error
727 auto getService = [&]() -> GattDeviceService {
728 if (!thisPtr) {
729 qCWarning(QT_BT_WINDOWS) << "LE controller was removed while getting native service";
730 return nullptr;
731 }
732
733 if (status != winrt::AsyncStatus::Completed) {
734 qCDebug(QT_BT_WINDOWS) << "Failed to get result of async service request";
735 return nullptr;
736 }
737
738 auto result = SAFE(op.GetResults());
739 if (!result) {
740 qErrnoWarning("Failed to get result of async service request");
741 return nullptr;
742 }
743
744 auto services = SAFE(result.Services());
745 if (!services) {
746 qErrnoWarning("Failed to extract services from the result");
747 return nullptr;
748 }
749
750 uint servicesCount = 0;
751 if (!TRY(servicesCount = services.Size())) {
752 qErrnoWarning("Failed to extract services count");
753 return nullptr;
754 }
755
756 if (servicesCount == 0) {
757 qCWarning(QT_BT_WINDOWS) << "No services found for Uuid" << serviceUuid;
758 return nullptr;
759 }
760
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.";
765 }
766
767 auto service = SAFE(services.GetAt(0));
768 if (!service) {
769 qCDebug(QT_BT_WINDOWS) << "Could not obtain native service for Uuid"
770 << serviceUuid;
771 }
772 return service;
773 };
774
775 auto service = getService();
776 // Update the cache and execute the callback in the main thread.
777 // We invoke the callback even with the null service in order to
778 // do the proper cleanup.
779 QMetaObject::invokeMethod(thisPtr.get(),
780 [thisPtr, callback, service, serviceUuid]() {
781 if (service)
782 thisPtr->m_openedServices.insert(serviceUuid, service);
783 callback(service); // Use the service in a custom callback
784 });
785 }));
786
787 return ok;
788}
789
790bool QLowEnergyControllerPrivateWinRT::getNativeCharacteristic(
791 const QBluetoothUuid &serviceUuid, const QBluetoothUuid &charUuid,
792 NativeCharacteristicCallback callback)
793{
794 // Directly execute the callback if the characteristic is already opened.
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());
799 return true;
800 }
801
802 auto pendingIt = m_pendingCharOperations.find(key);
803 if (pendingIt != m_pendingCharOperations.end()) {
804 // service or characteristic lookup is already in progress, no need
805 // to start a new one.
806 pendingIt->callbacks.append(std::move(callback));
807 return true;
808 }
809
810 // insert new operation to the list
811 const quint64 generation = ++m_charOperationsGeneration;
812 m_pendingCharOperations.insert(key, { generation, { std::move(callback) } });
813
814 QPointer<QLowEnergyControllerPrivateWinRT> thisPtr(this);
815
816 auto serviceCallback = [thisPtr, charUuid, key, generation](GattDeviceService service) {
817
818 // Cache the characteristic and execute the callback on the main thread.
819 // We need to call this lambda also in case of a failure with a null
820 // characteristic to make sure that the queue is cleared.
821 auto cacheCharAndExecuteCallback = [thisPtr, key, generation](
822 GattDeviceService service,
823 GattCharacteristic characteristic) {
824 if (!thisPtr)
825 return;
826 QMetaObject::invokeMethod(thisPtr.get(),
827 [thisPtr, key, generation, service, characteristic]() {
828 thisPtr->handleCharacteristic(key, generation, service,
829 characteristic);
830 });
831 };
832
833 if (!service) {
834 cacheCharAndExecuteCallback(nullptr, nullptr);
835 return;
836 }
837
838 auto characteristicRequestOp = SAFE(service.GetCharacteristicsForUuidAsync(GUID(charUuid)));
839 if (!characteristicRequestOp) {
840 qErrnoWarning("Could not start async characteristics request");
841 cacheCharAndExecuteCallback(service, nullptr);
842 return;
843 }
844
845 const bool ok = TRY(characteristicRequestOp.Completed(
846 [thisPtr, service, cacheCharAndExecuteCallback](
847 IAsyncOperation<GattCharacteristicsResult> const &op, winrt::AsyncStatus const status)
848 {
849 auto getCharacteristic = [&]() -> GattCharacteristic {
850 if (!thisPtr)
851 return nullptr;
852
853 if (status != winrt::AsyncStatus::Completed) {
854 qCDebug(QT_BT_WINDOWS) << "Failed to get result of async characteristic "
855 "operation";
856 return nullptr;
857 }
858
859 auto result = SAFE(op.GetResults());
860 if (!result) {
861 qErrnoWarning("Failed to get result of async characteristic operation");
862 return nullptr;
863 }
864
865 GattCommunicationStatus commStatus;
866 if (!TRY(commStatus = result.Status()) || commStatus != GattCommunicationStatus::Success) {
867 qErrnoWarning("Native characteristic operation failed.");
868 return nullptr;
869 }
870
871 auto characteristics = SAFE(result.Characteristics());
872 if (!characteristics) {
873 qErrnoWarning("Could not obtain characteristic list.");
874 return nullptr;
875 }
876
877 uint size;
878 if (!TRY(size = characteristics.Size())) {
879 qErrnoWarning("Could not obtain characteristic list's size.");
880 return nullptr;
881 }
882
883 if (size != 1)
884 qErrnoWarning("More than 1 characteristic found.");
885
886 auto characteristic = SAFE(characteristics.GetAt(0));
887 if (!characteristic)
888 qErrnoWarning("Could not obtain first characteristic for service");
889
890 return characteristic;
891 };
892
893 // use the characteristic in a custom callback
894 cacheCharAndExecuteCallback(service, getCharacteristic());
895 }));
896
897 if (!ok) {
898 qErrnoWarning("Characteristic request failed");
899 cacheCharAndExecuteCallback(service, nullptr);
900 }
901 };
902
903 if (!getNativeService(serviceUuid, serviceCallback)) {
904 qCDebug(QT_BT_WINDOWS) << "Failed to get native service for" << serviceUuid;
905 m_pendingCharOperations.remove(key); // all operations will fail anyway
906 return false;
907 }
908
909 return true;
910}
911
912void QLowEnergyControllerPrivateWinRT::registerForValueChanges(const QBluetoothUuid &serviceUuid,
913 const QBluetoothUuid &charUuid)
914{
915 qCDebug(QT_BT_WINDOWS) << "Registering characteristic" << charUuid << "in service"
916 << serviceUuid << "for value changes";
917 for (const ValueChangedEntry &entry : std::as_const(mValueChangedTokens)) {
918 GUID guuid{ 0 };
919 if (!TRY(guuid = entry.characteristic.Uuid()))
920 WARN_AND_CONTINUE("Could not obtain characteristic's Uuid");
921 if (QBluetoothUuid(guuid) == charUuid)
922 return;
923 }
924
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");
929
930 mValueChangedTokens.append(ValueChangedEntry(characteristic, token));
931 qCDebug(QT_BT_WINDOWS) << "Characteristic" << charUuid << "in service"
932 << serviceUuid << "registered for value changes";
933 };
934
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.";
940 }
941}
942
943void QLowEnergyControllerPrivateWinRT::unregisterFromValueChanges()
944{
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";
950 continue;
951 }
952 if (!TRY(entry.characteristic.ValueChanged(entry.token)))
953 qCWarning(QT_BT_WINDOWS) << "Unregistering from value changes for characteristic failed.";
954 }
955 mValueChangedTokens.clear();
956}
957
958void QLowEnergyControllerPrivateWinRT::onValueChange(GattCharacteristic characteristic, GattValueChangedEventArgs const &args)
959{
960 quint16 handle = 0;
961 if (!TRY(handle = characteristic.AttributeHandle()))
962 RETURN_MSG("Could not obtain characteristic's handle");
963
964 auto buffer = SAFE(args.CharacteristicValue());
965 if (!buffer)
966 RETURN_MSG("Could not obtain characteristic's value");
967
968 emit characteristicChanged(handle, byteArrayFromBuffer(buffer));
969}
970
971bool QLowEnergyControllerPrivateWinRT::registerForMtuChanges()
972{
973 if (!mDevice || !mGattSession)
974 return false;
975 qCDebug(QT_BT_WINDOWS) << __FUNCTION__;
976
977 QPointer<QLowEnergyControllerPrivateWinRT> thisPtr(this);
978 auto mtuChangeCallback = [thisPtr](GattSession session, winrt::IInspectable args) {
979 if (!thisPtr)
980 return;
981 QMetaObject::invokeMethod(thisPtr.get(), [thisPtr, session, args]() {
982 thisPtr->onMtuChange(session, args);
983 });
984 };
985
986 if (!TRY(mMtuChangedToken = mGattSession.MaxPduSizeChanged(mtuChangeCallback)))
987 RETURN_FALSE("Could not add MTU callback");
988 return true;
989}
990
991void QLowEnergyControllerPrivateWinRT::unregisterFromMtuChanges()
992{
993 qCDebug(QT_BT_WINDOWS) << __FUNCTION__;
994 if (mDevice && mGattSession && mMtuChangedToken) {
995 TRY(mGattSession.MaxPduSizeChanged(mMtuChangedToken));
996 mMtuChangedToken = { 0 };
997 }
998}
999
1000void QLowEnergyControllerPrivateWinRT::onMtuChange(GattSession session, winrt::IInspectable args)
1001{
1002 qCDebug(QT_BT_WINDOWS) << __FUNCTION__;
1003
1004 if (session != mGattSession) {
1005 qCWarning(QT_BT_WINDOWS) << "Got MTU changed event for wrong or outdated GattSession.";
1006 } else {
1007 Q_Q(QLowEnergyController);
1008 emit q->mtuChanged(mtu());
1009 }
1010}
1011
1012bool QLowEnergyControllerPrivateWinRT::registerForStatusChanges()
1013{
1014 if (!mDevice)
1015 return false;
1016
1017 qCDebug(QT_BT_WINDOWS) << __FUNCTION__;
1018
1019 QPointer<QLowEnergyControllerPrivateWinRT> thisPtr(this);
1020 auto statusChangeCallback = [thisPtr](BluetoothLEDevice dev, winrt::IInspectable args) {
1021 if (!thisPtr)
1022 return;
1023 QMetaObject::invokeMethod(thisPtr.get(), [thisPtr, dev, args]() {
1024 thisPtr->onStatusChange(dev, args);
1025 });
1026 };
1027
1028 if (!TRY(mStatusChangedToken = mDevice.ConnectionStatusChanged(statusChangeCallback)))
1029 RETURN_FALSE("Could not add status callback");
1030 return true;
1031}
1032
1033void QLowEnergyControllerPrivateWinRT::unregisterFromStatusChanges()
1034{
1035 qCDebug(QT_BT_WINDOWS) << __FUNCTION__;
1036 if (mDevice && mStatusChangedToken) {
1037 TRY(mDevice.ConnectionStatusChanged(mStatusChangedToken));
1038 mStatusChangedToken = { 0 };
1039 }
1040}
1041
1042void QLowEnergyControllerPrivateWinRT::onStatusChange(BluetoothLEDevice dev, winrt::IInspectable args)
1043{
1044 Q_Q(QLowEnergyController);
1045
1046 BluetoothConnectionStatus status;
1047 if (!TRY(status = dev.ConnectionStatus()))
1048 RETURN_MSG("Could not obtain connection status");
1049
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();
1060 clearAllServices();
1061 mGattSession = nullptr;
1062 mDevice = nullptr;
1063 setError(QLowEnergyController::RemoteHostClosedError);
1064 setState(QLowEnergyController::UnconnectedState);
1065 emit q->disconnected();
1066 }
1067}
1068
1069void QLowEnergyControllerPrivateWinRT::obtainIncludedServices(QSharedPointer<QLowEnergyServicePrivate> servicePointer, GattDeviceService service)
1070{
1071 Q_Q(QLowEnergyController);
1072
1073 auto result = SAFE(await(service.GetIncludedServicesAsync()));
1074 if (!result)
1075 RETURN_MSG("Could not obtain included services");
1076
1077 // The device can be disconnected by the time we return from await()
1078 if (state != QLowEnergyController::DiscoveringState)
1079 return;
1080
1081 GattCommunicationStatus status;
1082 if (!TRY(status = result.Status())) {
1083 qErrnoWarning("Could not obtain list of included services");
1084 return;
1085 }
1086
1087 auto includedServices = SAFE(result.Services());
1088 if (!includedServices)
1089 RETURN_MSG("Could not obtain service list");
1090
1091 uint count;
1092 if (!TRY(count = includedServices.Size()))
1093 RETURN_MSG("Could not obtain service list's size");
1094
1095 for (uint i = 0; i < count; ++i) {
1096
1097 auto includedService = SAFE(includedServices.GetAt(i));
1098 if (!includedService)
1099 WARN_AND_CONTINUE("Could not obtain service from list");
1100
1101 GUID guuid;
1102 if (!TRY(guuid = includedService.Uuid()))
1103 WARN_AND_CONTINUE("Could not obtain included service's Uuid");
1104
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);
1112 } else {
1114 priv->uuid = includedUuid;
1115 priv->setController(this);
1116
1117 includedPointer = QSharedPointer<QLowEnergyServicePrivate>(priv);
1118 serviceList.insert(includedUuid, includedPointer);
1119 }
1120 includedPointer->type |= QLowEnergyService::IncludedService;
1121 servicePointer->includedServices.append(includedUuid);
1122
1123 obtainIncludedServices(includedPointer, includedService);
1124
1125 emit q->serviceDiscovered(includedUuid);
1126 }
1127}
1128
1129void QLowEnergyControllerPrivateWinRT::onServiceDiscoveryFinished(IAsyncOperation<GattDeviceServicesResult> const &op, winrt::AsyncStatus status)
1130{
1131 // Check if the device is in the proper state, because it can already be
1132 // disconnected when the callback arrives.
1133 // Also the callback can theoretically come when the connection is
1134 // reestablisheed again (for example, if the user quickly clicks
1135 // "Disconnect" and then "Connect" again in some UI). But we can probably
1136 // omit such details, as we are connecting to the same device anyway.
1137 if (state != QLowEnergyController::DiscoveringState)
1138 return;
1139
1140 Q_Q(QLowEnergyController);
1141 if (status != winrt::AsyncStatus::Completed) {
1142 qCDebug(QT_BT_WINDOWS) << "Could not obtain services";
1143 return;
1144 }
1145
1146 auto result = SAFE(op.GetResults());
1147 if (!result)
1148 return handleConnectionError("Could not obtain service discovery result");
1149
1150 GattCommunicationStatus commStatus;
1151 if (!TRY(commStatus = result.Status()))
1152 return handleConnectionError("Could not obtain service discovery status");
1153
1154 if (commStatus != GattCommunicationStatus::Success)
1155 return;
1156
1157 auto deviceServices = SAFE(result.Services());
1158 if (!deviceServices)
1159 return handleConnectionError("Could not obtain service list");
1160
1161 uint serviceCount;
1162 if (!TRY(serviceCount = deviceServices.Size()))
1163 return handleConnectionError("Could not obtain service list size");
1164
1165 for (uint i = 0; i < serviceCount; ++i) {
1166
1167 auto deviceService = SAFE(deviceServices.GetAt(i));
1168 if (!deviceService)
1169 WARN_AND_CONTINUE("Could not obtain service");
1170
1171 GUID guuid;
1172 if (!TRY(guuid = deviceService.Uuid()))
1173 WARN_AND_CONTINUE("Could not obtain service's Uuid");
1174
1175 const QBluetoothUuid service(guuid);
1176 m_openedServices.insert(service, deviceService);
1177
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);
1184 } else {
1186 priv->uuid = service;
1187 priv->setController(this);
1188
1189 pointer = QSharedPointer<QLowEnergyServicePrivate>(priv);
1190 serviceList.insert(service, pointer);
1191 }
1192 pointer->type |= QLowEnergyService::PrimaryService;
1193
1194 obtainIncludedServices(pointer, deviceService);
1195 // The obtainIncludedServices method calls await(), so the device can be
1196 // disconnected by the time we return from it. TODO - rewrite in an
1197 // async way!
1198 if (state != QLowEnergyController::DiscoveringState) {
1199 emit q->discoveryFinished(); // Probably not needed when the device
1200 // is already disconnected?
1201 return;
1202 }
1203
1204 emit q->serviceDiscovered(service);
1205 }
1206
1207 setState(QLowEnergyController::DiscoveredState);
1208 emit q->discoveryFinished();
1209}
1210
1211void QLowEnergyControllerPrivateWinRT::clearAllServices()
1212{
1213 // These services will be closed in the respective
1214 // QWinRTLowEnergyServiceHandler workers (in background threads).
1215 for (auto &uuid : m_requestDetailsServiceUuids)
1216 m_openedServices.remove(uuid);
1217 m_requestDetailsServiceUuids.clear();
1218
1219 for (auto service : m_openedServices)
1220 TRY(service.Close());
1221 m_openedServices.clear();
1222 m_openedCharacteristics.clear();
1223 m_pendingCharOperations.clear();
1224}
1225
1226void QLowEnergyControllerPrivateWinRT::closeAndRemoveService(const QBluetoothUuid &uuid)
1227{
1228 auto record = m_openedServices.find(uuid);
1229 if (record != m_openedServices.end()) {
1230 auto service = record.value();
1231 m_openedServices.erase(record);
1232 if (service)
1233 TRY(service.Close());
1234 }
1235 removeCachedCharacteristics(uuid);
1236}
1237
1238void QLowEnergyControllerPrivateWinRT::handleCharacteristic(const NativeCharacteristicKey &key,
1239 quint64 generation,
1240 GattDeviceService service,
1241 GattCharacteristic characteristic)
1242{
1243 auto pendingOpIt = m_pendingCharOperations.find(key);
1244 if (pendingOpIt == m_pendingCharOperations.end() || pendingOpIt->generation != generation) {
1245 // This is a stale lookup callback, so the queue was already dropped.
1246 // A new queue (if it exists) refers to a newer lookup, so we do not
1247 // touch it.
1248 return;
1249 }
1250 const QList<NativeCharacteristicCallback> callbacks = std::move(pendingOpIt->callbacks);
1251 m_pendingCharOperations.erase(pendingOpIt);
1252 if (!characteristic)
1253 return; // nothing to execute
1254
1255 // only cache the characteristic if the service is still open
1256 auto serviceIt = m_openedServices.constFind(key.first);
1257 if (serviceIt != m_openedServices.cend() && serviceIt.value() == service)
1258 m_openedCharacteristics.insert(key, characteristic);
1259
1260 // execute all callbacks
1261 for (const auto &callback : callbacks)
1262 callback(characteristic);
1263}
1264
1265void QLowEnergyControllerPrivateWinRT::removeCachedCharacteristics(const QBluetoothUuid &serviceUuid)
1266{
1267 // If the characteristics is cached, then it cannot have a pending
1268 // operations queue, so we do not need to touch m_pendingCharOperations
1269 // here.
1270 auto it = m_openedCharacteristics.begin();
1271 while (it != m_openedCharacteristics.end()) {
1272 if (it.key().first == serviceUuid)
1273 it = m_openedCharacteristics.erase(it);
1274 else
1275 ++it;
1276 }
1277}
1278
1279void QLowEnergyControllerPrivateWinRT::discoverServices()
1280{
1281 qCDebug(QT_BT_WINDOWS) << "Service discovery initiated";
1282 // clear the previous services cache, as we request the services again
1283 clearAllServices();
1284
1285 auto asyncResult = SAFE(mDevice.GetGattServicesAsync());
1286 if (!asyncResult)
1287 return handleConnectionError("Could not obtain services");
1288
1289 QPointer<QLowEnergyControllerPrivateWinRT> thisPtr(this);
1290 auto discoveryCallback = [thisPtr](IAsyncOperation<GattDeviceServicesResult> const &op,
1291 winrt::AsyncStatus status) {
1292 if (!thisPtr)
1293 return;
1294 QMetaObject::invokeMethod(thisPtr.get(), [thisPtr, op, status]() {
1295 thisPtr->onServiceDiscoveryFinished(op, status);
1296 });
1297 };
1298
1299 if (!TRY(asyncResult.Completed(discoveryCallback)))
1300 return handleConnectionError("Could not register services discovery callback");
1301}
1302
1303void QLowEnergyControllerPrivateWinRT::discoverServiceDetails(
1304 const QBluetoothUuid &service, QLowEnergyService::DiscoveryMode mode)
1305{
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();
1310 return;
1311 }
1312
1313 // clear the cache to rediscover service details
1314 closeAndRemoveService(service);
1315
1316 auto serviceCallback = [service, mode, this](GattDeviceService deviceService) {
1317 discoverServiceDetailsHelper(service, mode, deviceService);
1318 };
1319
1320 if (!getNativeService(service, serviceCallback))
1321 qCDebug(QT_BT_WINDOWS) << "Could not obtain native service for uuid " << service;
1322}
1323
1324void QLowEnergyControllerPrivateWinRT::discoverServiceDetailsHelper(
1325 const QBluetoothUuid &service, QLowEnergyService::DiscoveryMode mode,
1326 GattDeviceService deviceService)
1327{
1328 auto reactOnDiscoveryError = [](QSharedPointer<QLowEnergyServicePrivate> service,
1329 const auto &msg)
1330 {
1331 qCDebug(QT_BT_WINDOWS) << msg;
1332 service->setError(QLowEnergyService::UnknownError);
1333 service->setState(QLowEnergyService::RemoteService);
1334 };
1335 //update service data
1336 QSharedPointer<QLowEnergyServicePrivate> pointer = serviceList.value(service);
1337 if (!pointer) {
1338 qCDebug(QT_BT_WINDOWS) << "Device was disconnected while doing service discovery";
1339 return;
1340 }
1341 qCDebug(QT_BT_WINDOWS_SERVICE_THREAD) << __FUNCTION__ << "Changing service pointer from thread"
1342 << QThread::currentThread();
1343 if (!deviceService)
1344 return reactOnDiscoveryError(pointer, "Device service was not discovered");
1345
1346 pointer->setState(QLowEnergyService::RemoteServiceDiscovering);
1347
1348 auto result = SAFE(await_forever(deviceService.GetIncludedServicesAsync()));
1349 if (!result)
1350 return reactOnDiscoveryError(pointer, "Could not obtain included service list");
1351
1352 if (SAFE(result.Status() != GattCommunicationStatus::Success))
1353 return reactOnDiscoveryError(pointer, "Obtaining list of included services failed");
1354
1355 auto deviceServices = SAFE(result.Services());
1356 if (!deviceServices)
1357 return reactOnDiscoveryError(pointer, "Could not obtain service list from result");
1358
1359 uint serviceCount;
1360 if (!TRY(serviceCount = deviceServices.Size()))
1361 return reactOnDiscoveryError(pointer, "Could not obtain included service list's size");
1362
1363 for (uint i = 0; i < serviceCount; ++i) {
1364
1365 auto includedService = SAFE(deviceServices.GetAt(i));
1366 if (!includedService)
1367 WARN_AND_CONTINUE("Could not obtain service from list");
1368
1369 GUID guuid;
1370 if (!TRY(guuid = includedService.Uuid()))
1371 WARN_AND_CONTINUE("Could not obtain service Uuid");
1372
1373 const QBluetoothUuid service(guuid);
1374 if (service.isNull()) {
1375 qCDebug(QT_BT_WINDOWS) << "Could not find service";
1376 continue;
1377 }
1378
1379 pointer->includedServices.append(service);
1380
1381 // update the type of the included service
1382 QSharedPointer<QLowEnergyServicePrivate> otherService = serviceList.value(service);
1383 if (!otherService.isNull())
1384 otherService->type |= QLowEnergyService::IncludedService;
1385 }
1386
1388 new QWinRTLowEnergyServiceHandler(service, deviceService, mode);
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);
1395 connect(this, &QLowEnergyControllerPrivateWinRT::abortConnection,
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();
1406 return;
1407 }
1408 m_requestDetailsServiceUuids.remove(service);
1409
1410 QSharedPointer<QLowEnergyServicePrivate> pointer = serviceList.value(service);
1411 pointer->startHandle = startHandle;
1412 pointer->endHandle = endHandle;
1413 pointer->characteristicList = charList;
1414
1415 for (const QBluetoothUuid &indicateChar : std::as_const(indicateChars))
1416 registerForValueChanges(service, indicateChar);
1417
1418 pointer->setState(QLowEnergyService::RemoteServiceDiscovered);
1419 });
1420 thread->start();
1421}
1422
1423void QLowEnergyControllerPrivateWinRT::startAdvertising(
1424 const QLowEnergyAdvertisingParameters &,
1425 const QLowEnergyAdvertisingData &,
1426 const QLowEnergyAdvertisingData &)
1427{
1428 setError(QLowEnergyController::AdvertisingError);
1429 Q_UNIMPLEMENTED();
1430}
1431
1432void QLowEnergyControllerPrivateWinRT::stopAdvertising()
1433{
1434 Q_UNIMPLEMENTED();
1435}
1436
1437void QLowEnergyControllerPrivateWinRT::requestConnectionUpdate(const QLowEnergyConnectionParameters &)
1438{
1439 Q_UNIMPLEMENTED();
1440}
1441
1442void QLowEnergyControllerPrivateWinRT::readCharacteristic(
1443 const QSharedPointer<QLowEnergyServicePrivate> service,
1444 const QLowEnergyHandle charHandle)
1445{
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);
1452 Q_UNIMPLEMENTED();
1453 return;
1454 }
1455
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);
1459 return;
1460 }
1461
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;
1465
1466 auto characteristicCallback = [charHandle, service, this](
1467 GattCharacteristic characteristic) {
1468 readCharacteristicHelper(service, charHandle, characteristic);
1469 };
1470
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);
1475 }
1476}
1477
1478void QLowEnergyControllerPrivateWinRT::readCharacteristicHelper(
1479 const QSharedPointer<QLowEnergyServicePrivate> service,
1480 const QLowEnergyHandle charHandle,
1481 GattCharacteristic characteristic)
1482{
1483 auto readOp = SAFE(characteristic.ReadValueAsync(BluetoothCacheMode::Uncached));
1484 if (!readOp)
1485 RETURN_SERVICE_ERROR("Could not read characteristic", service, QLowEnergyService::CharacteristicReadError);
1486
1487 auto readCompletedLambda = [charHandle, service]
1488 (IAsyncOperation<GattReadResult> const &op, winrt::AsyncStatus const status)
1489 {
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);
1493 return;
1494 }
1495 auto characteristicValue = SAFE(op.GetResults());
1496 if (!characteristicValue)
1497 RETURN_SERVICE_ERROR("Could not obtain result for characteristic", service, QLowEnergyService::CharacteristicReadError);
1498
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);
1504 return;
1505 };
1506
1507 if (!TRY(readOp.Completed(readCompletedLambda)))
1508 RETURN_SERVICE_ERROR("Could not register characteristic read callback", service, QLowEnergyService::CharacteristicReadError);
1509}
1510
1511void QLowEnergyControllerPrivateWinRT::readDescriptor(
1512 const QSharedPointer<QLowEnergyServicePrivate> service,
1513 const QLowEnergyHandle charHandle,
1514 const QLowEnergyHandle descHandle)
1515{
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);
1522 Q_UNIMPLEMENTED();
1523 return;
1524 }
1525
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);
1530 return;
1531 }
1532
1533 const auto charData = service->characteristicList.value(charHandle);
1534
1535 auto characteristicCallback = [charHandle, descHandle, service, this](
1536 GattCharacteristic characteristic) {
1537 readDescriptorHelper(service, charHandle, descHandle, characteristic);
1538 };
1539
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);
1544 }
1545}
1546
1547void QLowEnergyControllerPrivateWinRT::readDescriptorHelper(
1548 const QSharedPointer<QLowEnergyServicePrivate> service,
1549 const QLowEnergyHandle charHandle,
1550 const QLowEnergyHandle descHandle,
1551 GattCharacteristic characteristic)
1552{
1553 // Get native descriptor
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"
1557 << charHandle;
1558 }
1559 const auto descData = charData.descriptorList.value(descHandle);
1560 const QBluetoothUuid descUuid = descData.uuid;
1561 if (descUuid ==
1562 QBluetoothUuid(QBluetoothUuid::DescriptorType::ClientCharacteristicConfiguration)) {
1563
1564 auto readOp = SAFE(characteristic.ReadClientCharacteristicConfigurationDescriptorAsync());
1565 if (!readOp)
1566 RETURN_SERVICE_ERROR("Could not read client characteristic configuration", service, QLowEnergyService::DescriptorReadError);
1567
1568 auto readCompletedLambda = [charHandle, descHandle, service]
1569 (IAsyncOperation<ClientCharConfigDescriptorResult> const &op, winrt::AsyncStatus const status)
1570 {
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);
1574 return;
1575 }
1576
1577 auto iValue = SAFE(op.GetResults());
1578 if (!iValue)
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);
1583
1584 quint16 result = 0;
1585 bool correct = false;
1586 if (value & GattClientCharacteristicConfigurationDescriptorValue::Indicate) {
1587 result |= QLowEnergyCharacteristic::Indicate;
1588 correct = true;
1589 }
1590 if (value & GattClientCharacteristicConfigurationDescriptorValue::Notify) {
1591 result |= QLowEnergyCharacteristic::Notify;
1592 correct = true;
1593 }
1594 if (value == GattClientCharacteristicConfigurationDescriptorValue::None)
1595 correct = true;
1596 if (!correct) {
1597 qCDebug(QT_BT_WINDOWS) << "Descriptor" << descHandle
1598 << "read operation failed. Obtained unexpected value.";
1599 service->setError(QLowEnergyService::DescriptorReadError);
1600 return;
1601 }
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),
1608 descData.value);
1609 return;
1610 };
1611
1612 if (!TRY(readOp.Completed(readCompletedLambda)))
1613 RETURN_SERVICE_ERROR("Could not register descriptor read callback", service, QLowEnergyService::DescriptorReadError);
1614
1615 return;
1616 }
1617
1618 auto result = SAFE(await(characteristic.GetDescriptorsForUuidAsync(GUID(descData.uuid))));
1619 if (!result)
1620 RETURN_SERVICE_ERROR("Could not obtain descriptor for uuid", service, QLowEnergyService::DescriptorReadError);
1621
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);
1626 return;
1627 }
1628
1629 auto descriptors = SAFE(result.Descriptors());
1630 if (!descriptors)
1631 RETURN_SERVICE_ERROR("Could not obtain descriptor list", service, QLowEnergyService::DescriptorReadError);
1632
1633 uint size;
1634 if (!TRY(size = descriptors.Size()))
1635 RETURN_SERVICE_ERROR("Could not obtain descriptor list size", service, QLowEnergyService::DescriptorReadError);
1636
1637 if (size == 0) {
1638 qCWarning(QT_BT_WINDOWS) << "No descriptor with uuid" << descData.uuid << "was found.";
1639 service->setError(QLowEnergyService::DescriptorReadError);
1640 return;
1641 } else if (size > 1) {
1642 qCWarning(QT_BT_WINDOWS) << "There is more than 1 descriptor with uuid" << descData.uuid;
1643 }
1644
1645 auto descriptor = SAFE(descriptors.GetAt(0));
1646 if (!descriptor)
1647 RETURN_SERVICE_ERROR("Could not obtain descriptor from list", service, QLowEnergyService::DescriptorReadError);
1648
1649 auto readOp = SAFE(descriptor.ReadValueAsync(BluetoothCacheMode::Uncached));
1650 if (!readOp)
1651 RETURN_SERVICE_ERROR("Could not read descriptor value", service, QLowEnergyService::DescriptorReadError);
1652
1653 auto readCompletedLambda = [charHandle, descHandle, descUuid, service]
1654 (IAsyncOperation<GattReadResult> const &op, winrt::AsyncStatus const status)
1655 {
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);
1659 return;
1660 }
1661
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);
1666 return;
1667 }
1669 descData.uuid = descUuid;
1670 if (descData.uuid == QBluetoothUuid::DescriptorType::CharacteristicUserDescription)
1671 descData.value = byteArrayFromGattResult(descriptorValue, true);
1672 else
1673 descData.value = byteArrayFromGattResult(descriptorValue);
1674 service->characteristicList[charHandle].descriptorList[descHandle] = descData;
1675 emit service->descriptorRead(QLowEnergyDescriptor(service, charHandle, descHandle),
1676 descData.value);
1677 };
1678 if (!TRY(readOp.Completed(readCompletedLambda)))
1679 RETURN_SERVICE_ERROR("Could not register descriptor read callback", service, QLowEnergyService::DescriptorReadError);
1680}
1681
1682void QLowEnergyControllerPrivateWinRT::writeCharacteristic(
1683 const QSharedPointer<QLowEnergyServicePrivate> service,
1684 const QLowEnergyHandle charHandle,
1685 const QByteArray &newValue,
1686 QLowEnergyService::WriteMode mode)
1687{
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);
1694 Q_UNIMPLEMENTED();
1695 return;
1696 }
1697 if (!service->characteristicList.contains(charHandle)) {
1698 qCDebug(QT_BT_WINDOWS) << "Characteristic" << charHandle << "cannot be found in service"
1699 << service->uuid;
1700 service->setError(QLowEnergyService::CharacteristicWriteError);
1701 return;
1702 }
1703
1704 QLowEnergyServicePrivate::CharData charData = service->characteristicList.value(charHandle);
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;
1709
1710 auto characteristicCallback = [charHandle, service, newValue, writeWithResponse, this](
1711 GattCharacteristic characteristic) {
1712 writeCharacteristicHelper(service, charHandle, newValue, writeWithResponse,
1713 characteristic);
1714 };
1715
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);
1720 }
1721}
1722
1723void QLowEnergyControllerPrivateWinRT::writeCharacteristicHelper(
1724 const QSharedPointer<QLowEnergyServicePrivate> service,
1725 const QLowEnergyHandle charHandle, const QByteArray &newValue,
1726 bool writeWithResponse, GattCharacteristic characteristic)
1727{
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);
1732
1733 byte *bytes;
1734 if (!TRY(bytes = buffer.data()))
1735 RETURN_SERVICE_ERROR("Could not set buffer", service, QLowEnergyService::CharacteristicWriteError);
1736
1737 memcpy(bytes, newValue, length);
1738 if (!TRY(buffer.Length(length)))
1739 RETURN_SERVICE_ERROR("Could not set buffer length", service, QLowEnergyService::CharacteristicWriteError);
1740
1741 GattWriteOption option = writeWithResponse ? GattWriteOption::WriteWithResponse
1742 : GattWriteOption::WriteWithoutResponse;
1743 auto writeOp = SAFE(characteristic.WriteValueAsync(buffer, option));
1744 if (!writeOp)
1745 RETURN_SERVICE_ERROR("Could not write characteristic", service, QLowEnergyService::CharacteristicWriteError);
1746
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)
1752 {
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);
1757 return;
1758 }
1759
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);
1766 return;
1767 } else if (FAILED(hr)) {
1768 RETURN_SERVICE_ERROR("Could not obtain characteristic write result", service, QLowEnergyService::CharacteristicWriteError);
1769 }
1770
1771 if (result != GattCommunicationStatus::Success) {
1772 qCDebug(QT_BT_WINDOWS) << "Characteristic" << charHandle
1773 << "write operation failed (communication status)";
1774 service->setError(QLowEnergyService::CharacteristicWriteError);
1775 return;
1776 }
1777 // only update cache when property is readable. Otherwise it remains
1778 // empty.
1779 if (thisPtr && charData.properties & QLowEnergyCharacteristic::Read)
1780 thisPtr->updateValueOfCharacteristic(charHandle, newValue, false);
1781 if (writeWithResponse) {
1782 emit service->characteristicWritten(QLowEnergyCharacteristic(service, charHandle),
1783 newValue);
1784 }
1785 };
1786
1787 if (!TRY(writeOp.Completed(writeCompletedLambda)))
1788 RETURN_SERVICE_ERROR("Could not register characteristic write callback", service, QLowEnergyService::CharacteristicWriteError);
1789}
1790
1791void QLowEnergyControllerPrivateWinRT::writeDescriptor(
1792 const QSharedPointer<QLowEnergyServicePrivate> service,
1793 const QLowEnergyHandle charHandle,
1794 const QLowEnergyHandle descHandle,
1795 const QByteArray &newValue)
1796{
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);
1803 Q_UNIMPLEMENTED();
1804 return;
1805 }
1806
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);
1811 return;
1812 }
1813
1814 const auto charData = service->characteristicList.value(charHandle);
1815
1816 auto characteristicCallback = [descHandle, charHandle, service, newValue, this](
1817 GattCharacteristic characteristic) {
1818 writeDescriptorHelper(service, charHandle, descHandle, newValue, characteristic);
1819 };
1820
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);
1825 }
1826}
1827
1828void QLowEnergyControllerPrivateWinRT::writeDescriptorHelper(
1829 const QSharedPointer<QLowEnergyServicePrivate> service,
1830 const QLowEnergyHandle charHandle,
1831 const QLowEnergyHandle descHandle,
1832 const QByteArray &newValue,
1833 GattCharacteristic characteristic)
1834{
1835 // Get native descriptor
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;
1840 }
1841
1842 QLowEnergyServicePrivate::DescData descData = charData.descriptorList.value(descHandle);
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;
1860 } else {
1861 qCDebug(QT_BT_WINDOWS) << "Descriptor" << descHandle
1862 << "write operation failed: Invalid value";
1863 service->setError(QLowEnergyService::DescriptorWriteError);
1864 return;
1865 }
1866
1867 auto writeOp = SAFE(characteristic.WriteClientCharacteristicConfigurationDescriptorAsync(value));
1868 if (!writeOp)
1869 RETURN_SERVICE_ERROR("Could not write client characteristic configuration", service, QLowEnergyService::DescriptorWriteError);
1870
1871 QPointer<QLowEnergyControllerPrivateWinRT> thisPtr(this);
1872 auto writeCompletedLambda = [charHandle, descHandle, newValue, service, thisPtr]
1873 (IAsyncOperation<GattCommunicationStatus> const &op, winrt::AsyncStatus const status)
1874 {
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);
1878 return;
1879 }
1880
1881 GattCommunicationStatus result;
1882 if (!TRY(result = op.GetResults()))
1883 RETURN_SERVICE_ERROR("Could not obtain result for descriptor", service, QLowEnergyService::DescriptorWriteError);
1884
1885 if (result != GattCommunicationStatus::Success) {
1886 qCWarning(QT_BT_WINDOWS) << "Descriptor" << descHandle << "write operation failed";
1887 service->setError(QLowEnergyService::DescriptorWriteError);
1888 return;
1889 }
1890 if (thisPtr)
1891 thisPtr->updateValueOfDescriptor(charHandle, descHandle, newValue, false);
1892 emit service->descriptorWritten(QLowEnergyDescriptor(service, charHandle, descHandle),
1893 newValue);
1894 };
1895
1896 if (!TRY(writeOp.Completed(writeCompletedLambda)))
1897 RETURN_SERVICE_ERROR("Could not register descriptor write callback", service, QLowEnergyService::DescriptorWriteError);
1898
1899 return;
1900 }
1901
1902 auto result = SAFE(await(characteristic.GetDescriptorsForUuidAsync(GUID(descData.uuid))));
1903 if (!result)
1904 RETURN_SERVICE_ERROR("Could not obtain descriptor from Uuid", service, QLowEnergyService::DescriptorWriteError);
1905
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);
1910 return;
1911 }
1912
1913 auto descriptors = SAFE(result.Descriptors());
1914 if (!descriptors)
1915 RETURN_SERVICE_ERROR("Could not obtain list of descriptors", service, QLowEnergyService::DescriptorWriteError);
1916
1917 uint size;
1918 if (!TRY(size = descriptors.Size()))
1919 RETURN_SERVICE_ERROR("Could not obtain list of descriptors' size", service, QLowEnergyService::DescriptorWriteError);
1920
1921 if (size == 0) {
1922 qCWarning(QT_BT_WINDOWS) << "No descriptor with uuid" << descData.uuid << "was found.";
1923 return;
1924 } else if (size > 1) {
1925 qCWarning(QT_BT_WINDOWS) << "There is more than 1 descriptor with uuid" << descData.uuid;
1926 }
1927
1928 auto descriptor = SAFE(descriptors.GetAt(0));
1929 if (!descriptor)
1930 RETURN_SERVICE_ERROR("Could not obtain descriptor", service, QLowEnergyService::DescriptorWriteError);
1931
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);
1936
1937 byte *bytes;
1938 if (!TRY(bytes = buffer.data()))
1939 RETURN_SERVICE_ERROR("Could not set buffer", service, QLowEnergyService::CharacteristicWriteError);
1940
1941 memcpy(bytes, newValue, length);
1942 if (!TRY(buffer.Length(length)))
1943 RETURN_SERVICE_ERROR("Could not set buffer length", service, QLowEnergyService::CharacteristicWriteError);
1944
1945 auto writeOp = SAFE(descriptor.WriteValueAsync(buffer));
1946 if (!writeOp)
1947 RETURN_SERVICE_ERROR("Could not write descriptor value", service, QLowEnergyService::CharacteristicWriteError);
1948
1949 QPointer<QLowEnergyControllerPrivateWinRT> thisPtr(this);
1950 auto writeCompletedLambda = [charHandle, descHandle, newValue, service, thisPtr]
1951 (IAsyncOperation<GattCommunicationStatus> const &op, winrt::AsyncStatus const status)
1952 {
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);
1956 return;
1957 }
1958
1959 GattCommunicationStatus result;
1960 if (!TRY(result = op.GetResults()))
1961 RETURN_SERVICE_ERROR("Could not obtain result for descriptor", service, QLowEnergyService::DescriptorWriteError);
1962
1963 if (result != GattCommunicationStatus::Success) {
1964 qCDebug(QT_BT_WINDOWS) << "Descriptor" << descHandle << "write operation failed";
1965 service->setError(QLowEnergyService::DescriptorWriteError);
1966 return;
1967 }
1968 if (thisPtr)
1969 thisPtr->updateValueOfDescriptor(charHandle, descHandle, newValue, false);
1970 emit service->descriptorWritten(QLowEnergyDescriptor(service, charHandle, descHandle),
1971 newValue);
1972 };
1973
1974 if (!TRY(writeOp.Completed(writeCompletedLambda)))
1975 RETURN_SERVICE_ERROR("Could not register descriptor write callback", service, QLowEnergyService::DescriptorWriteError);
1976
1977}
1978
1979void QLowEnergyControllerPrivateWinRT::addToGenericAttributeList(const QLowEnergyServiceData &,
1981{
1982 Q_UNIMPLEMENTED();
1983}
1984
1985int QLowEnergyControllerPrivateWinRT::mtu() const
1986{
1987 uint16_t mtu = 23;
1988 if (!mGattSession) {
1989 qCDebug(QT_BT_WINDOWS) << "mtu queried before GattSession available. Using default mtu.";
1990 return mtu;
1991 }
1992
1993 if (!TRY(mtu = mGattSession.MaxPduSize()))
1994 RETURN_FALSE("could not obtain MTU size");
1995
1996 qCDebug(QT_BT_WINDOWS) << "mtu determined to be" << mtu;
1997 return mtu;
1998}
1999
2000void QLowEnergyControllerPrivateWinRT::handleCharacteristicChanged(
2001 quint16 charHandle, const QByteArray &data)
2002{
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())
2009 return;
2010
2011 qCDebug(QT_BT_WINDOWS) << "Characteristic change notification" << service->uuid
2012 << charHandle << data.toHex();
2013
2014 QLowEnergyCharacteristic characteristic = characteristicForHandle(charHandle);
2015 if (!characteristic.isValid()) {
2016 qCWarning(QT_BT_WINDOWS) << "characteristicChanged: Cannot find characteristic";
2017 return;
2018 }
2019
2020 // only update cache when property is readable. Otherwise it remains
2021 // empty.
2022 if (characteristic.properties() & QLowEnergyCharacteristic::Read)
2023 updateValueOfCharacteristic(characteristic.attributeHandle(),
2024 data, false);
2025 emit service->characteristicChanged(characteristic, data);
2026}
2027
2028void QLowEnergyControllerPrivateWinRT::handleServiceHandlerError(const QString &error)
2029{
2030 if (state != QLowEnergyController::DiscoveringState)
2031 return;
2032
2033 qCWarning(QT_BT_WINDOWS) << "Error while discovering services:" << error;
2034 setState(QLowEnergyController::UnconnectedState);
2035 setError(QLowEnergyController::ConnectionError);
2036}
2037
2038void QLowEnergyControllerPrivateWinRT::handleConnectionError(const char *logMessage)
2039{
2040 qCWarning(QT_BT_WINDOWS) << logMessage;
2041 setError(QLowEnergyController::ConnectionError);
2042 setState(QLowEnergyController::UnconnectedState);
2043 unregisterFromStatusChanges();
2044 unregisterFromMtuChanges();
2045}
2046
2047QT_END_NAMESPACE
2048
2049#include "qlowenergycontroller_winrt.moc"
void discoverServiceDetails(const QBluetoothUuid &service, QLowEnergyService::DiscoveryMode mode) override
void addToGenericAttributeList(const QLowEnergyServiceData &service, QLowEnergyHandle startHandle) override
void readDescriptor(const QSharedPointer< QLowEnergyServicePrivate > service, const QLowEnergyHandle charHandle, const QLowEnergyHandle descriptorHandle) override
void writeDescriptor(const QSharedPointer< QLowEnergyServicePrivate > service, const QLowEnergyHandle charHandle, const QLowEnergyHandle descriptorHandle, const QByteArray &newValue) override
void startAdvertising(const QLowEnergyAdvertisingParameters &params, 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 &params) override
void setController(QLowEnergyControllerPrivate *control)
void errorOccurred(const QString &error)
QHash< QLowEnergyHandle, QLowEnergyServicePrivate::CharData > mCharacteristicList
void errorOccured(const QString &error)
QLowEnergyService::DiscoveryMode mMode
#define SAFE(x)
#define HR(x)
#define TRY(x)
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)
#define RETURN_MSG(msg)