summaryrefslogtreecommitdiff
path: root/src/bluetooth/qbluetoothdevicediscoveryagent_winrt.cpp
blob: e0d3111a19521113865e6f07876409a4f5609640 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
// Copyright (C) 2022 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only

#include "qbluetoothdevicediscoveryagent.h"
#include "qbluetoothdevicediscoveryagent_p.h"
#include "qbluetoothaddress.h"
#include "qbluetoothuuid.h"

#include <QtBluetooth/private/qbluetoothdevicewatcher_winrt_p.h>
#include <QtBluetooth/private/qbluetoothutils_winrt_p.h>
#include <QtBluetooth/private/qtbluetoothglobal_p.h>

#include <QtCore/QLoggingCategory>
#include <QtCore/QMutex>
#include <QtCore/qendian.h>

#include <winrt/Windows.Devices.Bluetooth.h>
#include <winrt/Windows.Devices.Bluetooth.Advertisement.h>
#include <winrt/Windows.Devices.Bluetooth.Rfcomm.h>
#include <winrt/Windows.Devices.Bluetooth.GenericAttributeProfile.h>
#include <winrt/Windows.Devices.Enumeration.h>
#include <winrt/Windows.Foundation.h>
#include <winrt/Windows.Foundation.Collections.h>
#include <winrt/Windows.Storage.Streams.h>

using namespace winrt::Windows::Devices::Bluetooth;
using namespace winrt::Windows::Devices::Bluetooth::Advertisement;
using namespace winrt::Windows::Devices::Bluetooth::GenericAttributeProfile;
using namespace winrt::Windows::Devices::Bluetooth::Rfcomm;
using namespace winrt::Windows::Devices::Enumeration;
using namespace winrt::Windows::Foundation;
using namespace winrt::Windows::Storage::Streams;

QT_BEGIN_NAMESPACE

QT_IMPL_METATYPE_EXTERN(ManufacturerData)
QT_IMPL_METATYPE_EXTERN(ServiceData)

Q_DECLARE_LOGGING_CATEGORY(QT_BT_WINDOWS)

// Endianness conversion for QUuid::Id128Bytes doesn't exist in qtendian.h
inline QUuid::Id128Bytes qbswap(const QUuid::Id128Bytes src)
{
    QUuid::Id128Bytes dst;
    for (int i = 0; i < 16; i++)
        dst.data[i] = src.data[15 - i];
    return dst;
}

static QByteArray byteArrayFromBuffer(const IBuffer &buffer)
{
    const uint8_t *data = buffer.data();
    return QByteArray(reinterpret_cast<const char *>(data),
                      static_cast<qsizetype>(buffer.Length()));
}

static ManufacturerData extractManufacturerData(const BluetoothLEAdvertisement &ad)
{
    ManufacturerData ret;
    const auto data = ad.ManufacturerData();
    for (const auto &item : data) {
        const uint16_t id = item.CompanyId();
        const QByteArray bufferData = byteArrayFromBuffer(item.Data());
        if (ret.contains(id))
            qCWarning(QT_BT_WINDOWS) << "Company ID already present in manufacturer data.";
        ret.insert(id, bufferData);
    }
    return ret;
}

static ServiceData extractServiceData(const BluetoothLEAdvertisement &ad)
{
    static constexpr int serviceDataTypes[3] = { 0x16, 0x20, 0x21 };

    ServiceData ret;

    for (const auto &serviceDataType : serviceDataTypes) {
        const auto dataSections = ad.GetSectionsByType(serviceDataType);
        for (const auto &section : dataSections) {
            const unsigned char dataType = section.DataType();
            const QByteArray bufferData = byteArrayFromBuffer(section.Data());
            if (dataType == 0x16) {
                Q_ASSERT(bufferData.size() >= 2);
                ret.insert(QBluetoothUuid(qFromLittleEndian<quint16>(bufferData.constData())),
                           bufferData + 2);
            } else if (dataType == 0x20) {
                Q_ASSERT(bufferData.size() >= 4);
                ret.insert(QBluetoothUuid(qFromLittleEndian<quint32>(bufferData.constData())),
                           bufferData + 4);
            } else if (dataType == 0x21) {
                Q_ASSERT(bufferData.size() >= 16);
                ret.insert(QBluetoothUuid(qToBigEndian<QUuid::Id128Bytes>(
                                   qFromLittleEndian<QUuid::Id128Bytes>(bufferData.constData()))),
                           bufferData + 16);
            }
        }
    }

    return ret;
}

// Needed because there is no explicit conversion
static GUID fromWinRtGuid(const winrt::guid &guid)
{
    const GUID uuid {
        guid.Data1,
        guid.Data2,
        guid.Data3,
        { guid.Data4[0], guid.Data4[1], guid.Data4[2], guid.Data4[3],
          guid.Data4[4], guid.Data4[5], guid.Data4[6], guid.Data4[7] }
    };
    return uuid;
}

class AdvertisementWatcherWrapper : public QObject,
                                    public std::enable_shared_from_this<AdvertisementWatcherWrapper>
{
    Q_OBJECT
public:
    AdvertisementWatcherWrapper() {}
    ~AdvertisementWatcherWrapper()
    {
        stop();
    }
    void init()
    {
        m_watcher.ScanningMode(BluetoothLEScanningMode::Active);
    }
    void start() {
        subscribeToEvents();
        m_watcher.Start();
    }
    void stop()
    {
        if (canStop()) {
            unsubscribeFromEvents();
            m_watcher.Stop();
        }
    }

signals:
    // The signal will be emitted from a separate thread,
    // so we need to use Qt::QueuedConnection
    void advertisementDataReceived(quint64 address, qint16 rssi,
                                   const ManufacturerData &manufacturerData,
                                   const ServiceData &serviceData,
                                   const QList<QBluetoothUuid> &uuids);
private:
    void subscribeToEvents()
    {
        // The callbacks are triggered from separate threads. So we capture
        // thisPtr to make sure that the object is valid.
        auto thisPtr = shared_from_this();
        m_receivedToken = m_watcher.Received(
            [thisPtr](BluetoothLEAdvertisementWatcher,
                      BluetoothLEAdvertisementReceivedEventArgs args) {
                const uint64_t address = args.BluetoothAddress();
                const short rssi = args.RawSignalStrengthInDBm();
                const BluetoothLEAdvertisement ad = args.Advertisement();

                const ManufacturerData manufacturerData = extractManufacturerData(ad);
                const ServiceData serviceData = extractServiceData(ad);

                QList<QBluetoothUuid> serviceUuids;
                const auto guids = ad.ServiceUuids();
                for (const auto &guid : guids) {
                    const GUID uuid = fromWinRtGuid(guid);
                    serviceUuids.append(QBluetoothUuid(uuid));
                }

                emit thisPtr->advertisementDataReceived(address, rssi, manufacturerData,
                                                        serviceData, serviceUuids);
            });
    }
    void unsubscribeFromEvents()
    {
        m_watcher.Received(m_receivedToken);
    }
    bool canStop() const
    {
        const auto status = m_watcher.Status();
        return status == BluetoothLEAdvertisementWatcherStatus::Started
                || status == BluetoothLEAdvertisementWatcherStatus::Aborted;
    }

    BluetoothLEAdvertisementWatcher m_watcher;
    winrt::event_token m_receivedToken;
};

// Both constants are taken from Microsoft's docs:
// https://docs.microsoft.com/en-us/windows/uwp/devices-sensors/aep-service-class-ids
// Alternatively we could create separate watchers for paired and unpaired devices.
static const winrt::hstring ClassicDeviceSelector =
        L"System.Devices.Aep.ProtocolId:=\"{e0cbf06c-cd8b-4647-bb8a-263b43f0f974}\"";
// Do not use it for now, so comment out. Do not delete in case we want to reuse it.
//static const winrt::hstring LowEnergyDeviceSelector =
//        L"System.Devices.Aep.ProtocolId:=\"{bb7bb05e-5972-42b5-94fc-76eaa7084d49}\"";

class QWinRTBluetoothDeviceDiscoveryWorker : public QObject,
        public std::enable_shared_from_this<QWinRTBluetoothDeviceDiscoveryWorker>
{
    Q_OBJECT
public:
    QWinRTBluetoothDeviceDiscoveryWorker(QBluetoothDeviceDiscoveryAgent::DiscoveryMethods methods,
                                         int interval);
    ~QWinRTBluetoothDeviceDiscoveryWorker();
    void start();
    void stop();

private:
    void startDeviceDiscovery(QBluetoothDeviceDiscoveryAgent::DiscoveryMethod mode);

    std::shared_ptr<QBluetoothDeviceWatcherWinRT> createDeviceWatcher(winrt::hstring selector,
                                                                      int watcherId);
    void generateError(QBluetoothDeviceDiscoveryAgent::Error error, const char *msg = nullptr);
    void invokeDeviceFoundWithDebug(const QBluetoothDeviceInfo &info);
    void finishDiscovery();
    bool isFinished() const;

    // Bluetooth Classic handlers
    void getClassicDeviceFromId(const winrt::hstring &id);
    void handleClassicDevice(const BluetoothDevice &device);
    void handleRfcommServices(const RfcommDeviceServicesResult &servicesResult,
                              uint64_t address, const QString &name, uint32_t classOfDeviceInt);

    // Bluetooth Low Energy handlers
    void getLowEnergyDeviceFromId(const winrt::hstring &id);
    void handleLowEnergyDevice(const BluetoothLEDevice &device);
    void handleGattServices(const GattDeviceServicesResult &servicesResult,
                            QBluetoothDeviceInfo &info);

    // Bluetooth Low Energy Advertising handlers
    std::shared_ptr<AdvertisementWatcherWrapper> createAdvertisementWatcher();

    // invokable methods for handling finish conditions
    Q_INVOKABLE void decrementPendingDevicesCountAndCheckFinished(
            std::shared_ptr<QWinRTBluetoothDeviceDiscoveryWorker> worker);

Q_SIGNALS:
    void deviceFound(const QBluetoothDeviceInfo &info);
    void deviceDataChanged(const QBluetoothAddress &address, QBluetoothDeviceInfo::Fields,
                           qint16 rssi, ManufacturerData manufacturerData, ServiceData serviceData);
    void errorOccured(QBluetoothDeviceDiscoveryAgent::Error error);
    void scanFinished();

private slots:
    void onBluetoothDeviceFound(winrt::hstring deviceId, int watcherId);
    void onDeviceEnumerationCompleted(int watcherId);

    void onAdvertisementDataReceived(quint64 address, qint16 rssi,
                                     const ManufacturerData &manufacturerData,
                                     const ServiceData &serviceData,
                                     const QList<QBluetoothUuid> &uuids);

    void stopAdvertisementWatcher();

private:
    struct LEAdvertisingInfo {
        QList<QBluetoothUuid> services;
        ManufacturerData manufacturerData;
        ServiceData serviceData;
        qint16 rssi = 0;
    };

    quint8 requestedModes = 0;
    QMutex m_leDevicesMutex;
    QMap<quint64, LEAdvertisingInfo> m_foundLEDevicesMap;
    int m_pendingDevices = 0;

    static constexpr int ClassicWatcherId = 1;
    static constexpr int LowEnergyWatcherId = 2;

    std::shared_ptr<QBluetoothDeviceWatcherWinRT> m_classicWatcher;
    std::shared_ptr<QBluetoothDeviceWatcherWinRT> m_lowEnergyWatcher;
    std::shared_ptr<AdvertisementWatcherWrapper> m_advertisementWatcher;
    bool m_classicScanStarted = false;
    bool m_lowEnergyScanStarted = false;
    QTimer *m_leScanTimer = nullptr;
};

static void invokeDecrementPendingDevicesCountAndCheckFinished(
        std::shared_ptr<QWinRTBluetoothDeviceDiscoveryWorker> worker)
{
    QMetaObject::invokeMethod(worker.get(), "decrementPendingDevicesCountAndCheckFinished",
                              Qt::QueuedConnection,
                              Q_ARG(std::shared_ptr<QWinRTBluetoothDeviceDiscoveryWorker>,
                                    worker));
}

QWinRTBluetoothDeviceDiscoveryWorker::QWinRTBluetoothDeviceDiscoveryWorker(
        QBluetoothDeviceDiscoveryAgent::DiscoveryMethods methods, int interval)
    : requestedModes(methods)
{
    qRegisterMetaType<QBluetoothDeviceInfo>();
    qRegisterMetaType<QBluetoothDeviceInfo::Fields>();
    qRegisterMetaType<ManufacturerData>();
    qRegisterMetaType<std::shared_ptr<QWinRTBluetoothDeviceDiscoveryWorker>>();

    m_classicWatcher = createDeviceWatcher(ClassicDeviceSelector, ClassicWatcherId);
    // For LE scan use DeviceWatcher to handle only paired devices.
    // Non-paired devices will be found using BluetoothLEAdvertisementWatcher.
    const auto leSelector = BluetoothLEDevice::GetDeviceSelectorFromPairingState(true);
    m_lowEnergyWatcher = createDeviceWatcher(leSelector, LowEnergyWatcherId);
    m_advertisementWatcher = createAdvertisementWatcher();

    // Docs claim that a negative interval means that the backend handles it on its own
    if (interval < 0)
        interval = 40000;

    if (interval != 0) {
        m_leScanTimer = new QTimer(this);
        m_leScanTimer->setSingleShot(true);
        m_leScanTimer->setInterval(interval);
        connect(m_leScanTimer, &QTimer::timeout, this,
                &QWinRTBluetoothDeviceDiscoveryWorker::stopAdvertisementWatcher);
    }
}

QWinRTBluetoothDeviceDiscoveryWorker::~QWinRTBluetoothDeviceDiscoveryWorker()
{
    stop();
}

void QWinRTBluetoothDeviceDiscoveryWorker::start()
{
    if (requestedModes & QBluetoothDeviceDiscoveryAgent::ClassicMethod) {
        if (m_classicWatcher && m_classicWatcher->init()) {
            m_classicWatcher->start();
            m_classicScanStarted = true;
        } else {
            generateError(QBluetoothDeviceDiscoveryAgent::Error::UnknownError,
                          "Could not start classic device watcher");
        }
    }
    if (requestedModes & QBluetoothDeviceDiscoveryAgent::LowEnergyMethod) {
        if (m_lowEnergyWatcher && m_lowEnergyWatcher->init()) {
            m_lowEnergyWatcher->start();
            m_lowEnergyScanStarted = true;
        } else {
            generateError(QBluetoothDeviceDiscoveryAgent::Error::UnknownError,
                          "Could not start low energy device watcher");
        }
        if (m_advertisementWatcher) {
            m_advertisementWatcher->init();
            m_advertisementWatcher->start();
            if (m_leScanTimer)
                m_leScanTimer->start();
        } else {
            generateError(QBluetoothDeviceDiscoveryAgent::Error::UnknownError,
                          "Could not start low energy advertisement watcher");
        }
    }

    qCDebug(QT_BT_WINDOWS) << "Worker started";
}

void QWinRTBluetoothDeviceDiscoveryWorker::stop()
{
    if (m_leScanTimer && m_leScanTimer->isActive())
        m_leScanTimer->stop();
    m_classicWatcher->stop();
    m_lowEnergyWatcher->stop();
    m_advertisementWatcher->stop();
}

void QWinRTBluetoothDeviceDiscoveryWorker::finishDiscovery()
{
    stop();
    emit scanFinished();
}

bool QWinRTBluetoothDeviceDiscoveryWorker::isFinished() const
{
    // If the interval is set to 0, we do not start a timer, and that means
    // that we need to wait for the user to explicitly call stop()
    return (m_pendingDevices == 0) && !m_lowEnergyScanStarted && !m_classicScanStarted
            && (m_leScanTimer && !m_leScanTimer->isActive());
}

void QWinRTBluetoothDeviceDiscoveryWorker::onBluetoothDeviceFound(winrt::hstring deviceId, int watcherId)
{
    if (watcherId == ClassicWatcherId)
        getClassicDeviceFromId(deviceId);
    else if (watcherId == LowEnergyWatcherId)
        getLowEnergyDeviceFromId(deviceId);
}

void QWinRTBluetoothDeviceDiscoveryWorker::onDeviceEnumerationCompleted(int watcherId)
{
    qCDebug(QT_BT_WINDOWS) << (watcherId == ClassicWatcherId ? "BT" : "BTLE")
                           << "enumeration completed";
    if (watcherId == ClassicWatcherId) {
        m_classicWatcher->stop();
        m_classicScanStarted = false;
    } else if (watcherId == LowEnergyWatcherId) {
        m_lowEnergyWatcher->stop();
        m_lowEnergyScanStarted = false;
    }
    if (isFinished())
        finishDiscovery();
}

// this function executes in main worker thread
void QWinRTBluetoothDeviceDiscoveryWorker::onAdvertisementDataReceived(
        quint64 address, qint16 rssi, const ManufacturerData &manufacturerData,
        const ServiceData &serviceData, const QList<QBluetoothUuid> &uuids)
{
    // Merge newly found services with list of currently found ones
    {
        QMutexLocker locker(&m_leDevicesMutex);
        if (m_foundLEDevicesMap.contains(address)) {
            QBluetoothDeviceInfo::Fields changedFields = QBluetoothDeviceInfo::Field::None;
            const LEAdvertisingInfo adInfo = m_foundLEDevicesMap.value(address);
            QList<QBluetoothUuid> foundServices = adInfo.services;
            if (adInfo.rssi != rssi) {
                m_foundLEDevicesMap[address].rssi = rssi;
                changedFields.setFlag(QBluetoothDeviceInfo::Field::RSSI);
            }
            if (adInfo.manufacturerData != manufacturerData) {
                m_foundLEDevicesMap[address].manufacturerData.insert(manufacturerData);
                if (adInfo.manufacturerData != m_foundLEDevicesMap[address].manufacturerData)
                    changedFields.setFlag(QBluetoothDeviceInfo::Field::ManufacturerData);
            }
            if (adInfo.serviceData != serviceData) {
                m_foundLEDevicesMap[address].serviceData.insert(serviceData);
                if (adInfo.serviceData != m_foundLEDevicesMap[address].serviceData)
                    changedFields.setFlag((QBluetoothDeviceInfo::Field::ServiceData));
            }
            bool newServiceAdded = false;
            for (const QBluetoothUuid &uuid : std::as_const(uuids)) {
                if (!foundServices.contains(uuid)) {
                    foundServices.append(uuid);
                    newServiceAdded = true;
                }
            }
            if (!newServiceAdded) {
                if (!changedFields.testFlag(QBluetoothDeviceInfo::Field::None)) {
                    QMetaObject::invokeMethod(this, "deviceDataChanged", Qt::AutoConnection,
                                              Q_ARG(QBluetoothAddress, QBluetoothAddress(address)),
                                              Q_ARG(QBluetoothDeviceInfo::Fields, changedFields),
                                              Q_ARG(qint16, rssi),
                                              Q_ARG(ManufacturerData, manufacturerData),
                                              Q_ARG(ServiceData, serviceData));
                }
            }
            m_foundLEDevicesMap[address].services = foundServices;
        } else {
            LEAdvertisingInfo info;
            info.services = std::move(uuids);
            info.manufacturerData = std::move(manufacturerData);
            info.serviceData = std::move(serviceData);
            info.rssi = rssi;
            m_foundLEDevicesMap.insert(address, info);
        }
    }
    ++m_pendingDevices; // as if we discovered a new LE device
    auto thisPtr = shared_from_this();
    auto asyncOp = BluetoothLEDevice::FromBluetoothAddressAsync(address);
    asyncOp.Completed([thisPtr, address](auto &&op, AsyncStatus status) {
        if (thisPtr) {
            if (status == AsyncStatus::Completed) {
                BluetoothLEDevice device = op.GetResults();
                if (device) {
                    thisPtr->handleLowEnergyDevice(device);
                    return;
                }
            }
            // status != Completed or failed to extract result
            qCDebug(QT_BT_WINDOWS) << "Failed to get LE device from address"
                                   << QBluetoothAddress(address);
            invokeDecrementPendingDevicesCountAndCheckFinished(thisPtr);
        }
    });
}

void QWinRTBluetoothDeviceDiscoveryWorker::stopAdvertisementWatcher()
{
    m_advertisementWatcher->stop();
    if (isFinished())
        finishDiscovery();
}

std::shared_ptr<QBluetoothDeviceWatcherWinRT>
QWinRTBluetoothDeviceDiscoveryWorker::createDeviceWatcher(winrt::hstring selector, int watcherId)
{
    auto watcher = std::make_shared<QBluetoothDeviceWatcherWinRT>(
                watcherId, selector, DeviceInformationKind::AssociationEndpoint);
    if (watcher) {
        connect(watcher.get(), &QBluetoothDeviceWatcherWinRT::deviceAdded,
                this, &QWinRTBluetoothDeviceDiscoveryWorker::onBluetoothDeviceFound,
                Qt::QueuedConnection);
        connect(watcher.get(), &QBluetoothDeviceWatcherWinRT::enumerationCompleted,
                this, &QWinRTBluetoothDeviceDiscoveryWorker::onDeviceEnumerationCompleted,
                Qt::QueuedConnection);
    }
    return watcher;
}

void QWinRTBluetoothDeviceDiscoveryWorker::generateError(
        QBluetoothDeviceDiscoveryAgent::Error error, const char *msg)
{
    emit errorOccured(error);
    qCWarning(QT_BT_WINDOWS) << msg;
}

void QWinRTBluetoothDeviceDiscoveryWorker::invokeDeviceFoundWithDebug(const QBluetoothDeviceInfo &info)
{
    qCDebug(QT_BT_WINDOWS) << "Discovered BTLE device: " << info.address() << info.name()
                           << "Num UUIDs" << info.serviceUuids().size() << "RSSI:" << info.rssi()
                           << "Num manufacturer data" << info.manufacturerData().size()
                           << "Num service data" << info.serviceData().size();

    QMetaObject::invokeMethod(this, "deviceFound", Qt::AutoConnection,
                              Q_ARG(QBluetoothDeviceInfo, info));
}

// this function executes in main worker thread
void QWinRTBluetoothDeviceDiscoveryWorker::getClassicDeviceFromId(const winrt::hstring &id)
{
    ++m_pendingDevices;
    auto thisPtr = shared_from_this();
    auto asyncOp = BluetoothDevice::FromIdAsync(id);
    asyncOp.Completed([thisPtr](auto &&op, AsyncStatus status) {
        if (thisPtr) {
            if (status == AsyncStatus::Completed) {
                BluetoothDevice device = op.GetResults();
                if (device) {
                    thisPtr->handleClassicDevice(device);
                    return;
                }
            }
            // status != Completed or failed to extract result
            qCDebug(QT_BT_WINDOWS) << "Failed to get Classic device from id";
            invokeDecrementPendingDevicesCountAndCheckFinished(thisPtr);
        }
    });
}

// this is a callback - executes in a new thread
void QWinRTBluetoothDeviceDiscoveryWorker::handleClassicDevice(const BluetoothDevice &device)
{
    const uint64_t address = device.BluetoothAddress();
    const std::wstring name { device.Name() }; // via operator std::wstring_view()
    const QString btName = QString::fromStdWString(name);
    const uint32_t deviceClass = device.ClassOfDevice().RawValue();
    auto thisPtr = shared_from_this();
    auto asyncOp = device.GetRfcommServicesAsync();
    asyncOp.Completed([thisPtr, address, btName, deviceClass](auto &&op, AsyncStatus status) {
        if (thisPtr) {
            if (status == AsyncStatus::Completed) {
                auto servicesResult = op.GetResults();
                if (servicesResult) {
                    thisPtr->handleRfcommServices(servicesResult, address, btName, deviceClass);
                    return;
                }
            }
            // Failed to get services
            qCDebug(QT_BT_WINDOWS) << "Failed to get RFCOMM services for device" << btName;
            invokeDecrementPendingDevicesCountAndCheckFinished(thisPtr);
        }
    });
}

// this is a callback - executes in a new thread
void QWinRTBluetoothDeviceDiscoveryWorker::handleRfcommServices(
        const RfcommDeviceServicesResult &servicesResult, uint64_t address,
        const QString &name, uint32_t classOfDeviceInt)
{
    // need to perform the check even if some of the operations fails
    auto shared = shared_from_this();
    auto guard = qScopeGuard([shared]() {
        invokeDecrementPendingDevicesCountAndCheckFinished(shared);
    });
    Q_UNUSED(guard); // to suppress warning

    const auto error = servicesResult.Error();
    if (error != BluetoothError::Success) {
        qCWarning(QT_BT_WINDOWS) << "Obtain device services completed with BluetoothError"
                                 << static_cast<int>(error);
        return;
    }

    const auto services = servicesResult.Services();
    QList<QBluetoothUuid> uuids;
    for (const auto &service : services) {
        const auto serviceId = service.ServiceId();
        const GUID uuid = fromWinRtGuid(serviceId.Uuid());
        uuids.append(QBluetoothUuid(uuid));
    }

    const QBluetoothAddress btAddress(address);

    qCDebug(QT_BT_WINDOWS) << "Discovered BT device: " << btAddress << name
                           << "Num UUIDs" << uuids.size();

    QBluetoothDeviceInfo info(btAddress, name, classOfDeviceInt);
    info.setCoreConfigurations(QBluetoothDeviceInfo::BaseRateCoreConfiguration);
    info.setServiceUuids(uuids);
    info.setCached(true);

    QMetaObject::invokeMethod(this, "deviceFound", Qt::AutoConnection,
                              Q_ARG(QBluetoothDeviceInfo, info));
}

void QWinRTBluetoothDeviceDiscoveryWorker::decrementPendingDevicesCountAndCheckFinished(
        std::shared_ptr<QWinRTBluetoothDeviceDiscoveryWorker> worker)
{
    --m_pendingDevices;
    if (isFinished())
        finishDiscovery();
    // Worker is passed here simply to make sure that the object is still alive
    // when we call this method via QObject::invoke().
    Q_UNUSED(worker)
}

// this function executes in main worker thread
void QWinRTBluetoothDeviceDiscoveryWorker::getLowEnergyDeviceFromId(const winrt::hstring &id)
{
    ++m_pendingDevices;
    auto asyncOp = BluetoothLEDevice::FromIdAsync(id);
    auto thisPtr = shared_from_this();
    asyncOp.Completed([thisPtr](auto &&op, AsyncStatus status) {
        if (thisPtr) {
            if (status == AsyncStatus::Completed) {
                BluetoothLEDevice device = op.GetResults();
                if (device) {
                    thisPtr->handleLowEnergyDevice(device);
                    return;
                }
            }
            // status != Completed or failed to extract result
            qCDebug(QT_BT_WINDOWS) << "Failed to get LE device from id";
            invokeDecrementPendingDevicesCountAndCheckFinished(thisPtr);
        }
    });
}

// this is a callback - executes in a new thread
void QWinRTBluetoothDeviceDiscoveryWorker::handleLowEnergyDevice(const BluetoothLEDevice &device)
{
    const uint64_t address = device.BluetoothAddress();
    const std::wstring name { device.Name() }; // via operator std::wstring_view()
    const QString btName = QString::fromStdWString(name);
    const bool isPaired = device.DeviceInformation().Pairing().IsPaired();

    m_leDevicesMutex.lock();
    const LEAdvertisingInfo adInfo = m_foundLEDevicesMap.value(address);
    m_leDevicesMutex.unlock();
    const ManufacturerData manufacturerData = adInfo.manufacturerData;
    const ServiceData serviceData = adInfo.serviceData;
    const qint16 rssi = adInfo.rssi;

    QBluetoothDeviceInfo info(QBluetoothAddress(address), btName, 0);
    info.setCoreConfigurations(QBluetoothDeviceInfo::LowEnergyCoreConfiguration);
    info.setRssi(rssi);
    for (quint16 key : manufacturerData.keys())
        info.setManufacturerData(key, manufacturerData.value(key));
    for (QBluetoothUuid key : serviceData.keys())
        info.setServiceData(key, serviceData.value(key));
    info.setCached(true);

    // Use the services obtained from the advertisement data if the device is not paired
    if (!isPaired) {
        info.setServiceUuids(adInfo.services);
        invokeDecrementPendingDevicesCountAndCheckFinished(shared_from_this());
        invokeDeviceFoundWithDebug(info);
    } else {
        auto asyncOp = device.GetGattServicesAsync();
        auto thisPtr = shared_from_this();
        asyncOp.Completed([thisPtr, info](auto &&op, AsyncStatus status) mutable {
            if (status == AsyncStatus::Completed) {
                auto servicesResult = op.GetResults();
                if (servicesResult) {
                    thisPtr->handleGattServices(servicesResult, info);
                    return;
                }
            }
            // Failed to get services
            qCDebug(QT_BT_WINDOWS) << "Failed to get GATT services for device" << info.name();
            invokeDecrementPendingDevicesCountAndCheckFinished(thisPtr);
        });
    }
}

// this is a callback - executes in a new thread
void QWinRTBluetoothDeviceDiscoveryWorker::handleGattServices(
        const GattDeviceServicesResult &servicesResult, QBluetoothDeviceInfo &info)
{
    // need to perform the check even if some of the operations fails
    auto shared = shared_from_this();
    auto guard = qScopeGuard([shared]() {
        invokeDecrementPendingDevicesCountAndCheckFinished(shared);
    });
    Q_UNUSED(guard); // to suppress warning

    const auto status = servicesResult.Status();
    if (status == GattCommunicationStatus::Success) {
        const auto services = servicesResult.Services();
        QList<QBluetoothUuid> uuids;
        for (const auto &service : services) {
            const GUID uuid = fromWinRtGuid(service.Uuid());
            uuids.append(QBluetoothUuid(uuid));
        }
        info.setServiceUuids(uuids);
    } else {
        qCWarning(QT_BT_WINDOWS) << "Obtaining LE services finished with status"
                                 << static_cast<int>(status);
    }
    invokeDeviceFoundWithDebug(info);
}

std::shared_ptr<AdvertisementWatcherWrapper>
QWinRTBluetoothDeviceDiscoveryWorker::createAdvertisementWatcher()
{
    auto watcher = std::make_shared<AdvertisementWatcherWrapper>();
    if (watcher) {
        connect(watcher.get(), &AdvertisementWatcherWrapper::advertisementDataReceived,
                this, &QWinRTBluetoothDeviceDiscoveryWorker::onAdvertisementDataReceived,
                Qt::QueuedConnection);
    }
    return watcher;
}

QBluetoothDeviceDiscoveryAgentPrivate::QBluetoothDeviceDiscoveryAgentPrivate(
        const QBluetoothAddress &deviceAdapter, QBluetoothDeviceDiscoveryAgent *parent)
    : q_ptr(parent), adapterAddress(deviceAdapter)
{
    mainThreadCoInit(this);
}

QBluetoothDeviceDiscoveryAgentPrivate::~QBluetoothDeviceDiscoveryAgentPrivate()
{
    disconnectAndClearWorker();
    mainThreadCoUninit(this);
}

bool QBluetoothDeviceDiscoveryAgentPrivate::isActive() const
{
    return worker != nullptr;
}

QBluetoothDeviceDiscoveryAgent::DiscoveryMethods QBluetoothDeviceDiscoveryAgent::supportedDiscoveryMethods()
{
    return (ClassicMethod | LowEnergyMethod);
}

void QBluetoothDeviceDiscoveryAgentPrivate::start(QBluetoothDeviceDiscoveryAgent::DiscoveryMethods methods)
{
    QBluetoothLocalDevice adapter(adapterAddress);
    if (!adapter.isValid()) {
        qCWarning(QT_BT_WINDOWS) << "Cannot find Bluetooth adapter for device search";
        lastError = QBluetoothDeviceDiscoveryAgent::InvalidBluetoothAdapterError;
        errorString = QBluetoothDeviceDiscoveryAgent::tr("Cannot find valid Bluetooth adapter.");
        emit q_ptr->errorOccurred(lastError);
        return;
    } else if (adapter.hostMode() == QBluetoothLocalDevice::HostPoweredOff) {
        qCWarning(QT_BT_WINDOWS) << "Bluetooth adapter powered off";
        lastError = QBluetoothDeviceDiscoveryAgent::PoweredOffError;
        errorString = QBluetoothDeviceDiscoveryAgent::tr("Bluetooth adapter powered off.");
        emit q_ptr->errorOccurred(lastError);
        return;
    }

    if (worker)
        return;

    worker = std::make_shared<QWinRTBluetoothDeviceDiscoveryWorker>(methods,
                                                                    lowEnergySearchTimeout);
    lastError = QBluetoothDeviceDiscoveryAgent::NoError;
    errorString.clear();
    discoveredDevices.clear();
    connect(worker.get(), &QWinRTBluetoothDeviceDiscoveryWorker::deviceFound,
            this, &QBluetoothDeviceDiscoveryAgentPrivate::registerDevice);
    connect(worker.get(), &QWinRTBluetoothDeviceDiscoveryWorker::deviceDataChanged,
            this, &QBluetoothDeviceDiscoveryAgentPrivate::updateDeviceData);
    connect(worker.get(), &QWinRTBluetoothDeviceDiscoveryWorker::errorOccured,
            this, &QBluetoothDeviceDiscoveryAgentPrivate::onErrorOccured);
    connect(worker.get(), &QWinRTBluetoothDeviceDiscoveryWorker::scanFinished,
            this, &QBluetoothDeviceDiscoveryAgentPrivate::onScanFinished);
    worker->start();
}

void QBluetoothDeviceDiscoveryAgentPrivate::stop()
{
    Q_Q(QBluetoothDeviceDiscoveryAgent);
    if (worker) {
        worker->stop();
        disconnectAndClearWorker();
        emit q->canceled();
    }
}

void QBluetoothDeviceDiscoveryAgentPrivate::registerDevice(const QBluetoothDeviceInfo &info)
{
    Q_Q(QBluetoothDeviceDiscoveryAgent);

    for (QList<QBluetoothDeviceInfo>::iterator iter = discoveredDevices.begin();
        iter != discoveredDevices.end(); ++iter) {
        if (iter->address() == info.address()) {
            qCDebug(QT_BT_WINDOWS) << "Updating device" << iter->name() << iter->address();
            // merge service uuids
            QList<QBluetoothUuid> uuids = iter->serviceUuids();
            uuids.append(info.serviceUuids());
            const QSet<QBluetoothUuid> uuidSet(uuids.begin(), uuids.end());
            if (iter->serviceUuids().size() != uuidSet.size())
                iter->setServiceUuids(uuidSet.values().toVector());
            if (iter->coreConfigurations() != info.coreConfigurations())
                iter->setCoreConfigurations(QBluetoothDeviceInfo::BaseRateAndLowEnergyCoreConfiguration);
            return;
        }
    }

    discoveredDevices << info;
    emit q->deviceDiscovered(info);
}

void QBluetoothDeviceDiscoveryAgentPrivate::updateDeviceData(const QBluetoothAddress &address,
                                                             QBluetoothDeviceInfo::Fields fields,
                                                             qint16 rssi,
                                                             ManufacturerData manufacturerData,
                                                             ServiceData serviceData)
{
    if (fields.testFlag(QBluetoothDeviceInfo::Field::None))
        return;

    Q_Q(QBluetoothDeviceDiscoveryAgent);
    for (QList<QBluetoothDeviceInfo>::iterator iter = discoveredDevices.begin();
        iter != discoveredDevices.end(); ++iter) {
        if (iter->address() == address) {
            qCDebug(QT_BT_WINDOWS) << "Updating data for device" << iter->name() << iter->address();
            if (fields.testFlag(QBluetoothDeviceInfo::Field::RSSI))
                iter->setRssi(rssi);
            if (fields.testFlag(QBluetoothDeviceInfo::Field::ManufacturerData))
                for (quint16 key : manufacturerData.keys())
                    iter->setManufacturerData(key, manufacturerData.value(key));
            if (fields.testFlag(QBluetoothDeviceInfo::Field::ServiceData))
                for (QBluetoothUuid key : serviceData.keys())
                    iter->setServiceData(key, serviceData.value(key));
            emit q->deviceUpdated(*iter, fields);
            return;
        }
    }
}

void QBluetoothDeviceDiscoveryAgentPrivate::onErrorOccured(QBluetoothDeviceDiscoveryAgent::Error e)
{
    Q_Q(QBluetoothDeviceDiscoveryAgent);
    lastError = e;
    emit q->errorOccurred(e);
}

void QBluetoothDeviceDiscoveryAgentPrivate::onScanFinished()
{
    Q_Q(QBluetoothDeviceDiscoveryAgent);
    disconnectAndClearWorker();
    emit q->finished();
}

void QBluetoothDeviceDiscoveryAgentPrivate::disconnectAndClearWorker()
{
    if (!worker)
        return;

    disconnect(worker.get(), &QWinRTBluetoothDeviceDiscoveryWorker::scanFinished,
               this, &QBluetoothDeviceDiscoveryAgentPrivate::onScanFinished);
    disconnect(worker.get(), &QWinRTBluetoothDeviceDiscoveryWorker::deviceFound,
               this, &QBluetoothDeviceDiscoveryAgentPrivate::registerDevice);
    disconnect(worker.get(), &QWinRTBluetoothDeviceDiscoveryWorker::deviceDataChanged,
               this, &QBluetoothDeviceDiscoveryAgentPrivate::updateDeviceData);
    disconnect(worker.get(), &QWinRTBluetoothDeviceDiscoveryWorker::errorOccured,
               this, &QBluetoothDeviceDiscoveryAgentPrivate::onErrorOccured);

    worker = nullptr;
}

QT_END_NAMESPACE

#include <qbluetoothdevicediscoveryagent_winrt.moc>