summaryrefslogtreecommitdiffstats
path: root/tests/manual/qlowenergycontroller/tst_qlowenergycontroller_device.cpp
blob: d24ceffc3888c183b161ec876af2ab50d064960e (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
/****************************************************************************
**
** Copyright (C) 2021 The Qt Company Ltd.
** Contact: https://www.qt.io/licensing/
**
** This file is part of the QtBluetooth module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:GPL-EXCEPT$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see https://www.qt.io/terms-conditions. For further
** information use the contact form at https://www.qt.io/contact-us.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3 as published by the Free Software
** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
** included in the packaging of this file. Please review the following
** information to ensure the GNU General Public License requirements will
** be met: https://www.gnu.org/licenses/gpl-3.0.html.
**
** $QT_END_LICENSE$
**
****************************************************************************/

#include <QObject>
#include <QtGlobal>
#include <QTest>
#include <QBluetoothAddress>
#include <QBluetoothDeviceDiscoveryAgent>
#include <QSignalSpy>
#include <QLowEnergyController>
#include <QLoggingCategory>
#include <QScopeGuard>
#include <QBluetoothLocalDevice>

static const QLatin1String largeCharacteristicServiceUuid("1f85e37c-ac16-11eb-ae5c-93d3a763feed");
static const QLatin1String largeCharacteristicCharUuid("40e4f68e-ac16-11eb-9956-cfe55a8c370c");

static const QLatin1String platformIdentifierServiceUuid("4a92cb7f-5031-4a09-8304-3e89413f458d");
static const QLatin1String platformIdentifierCharUuid("6b0ecf7c-5f09-4c87-aaab-bb49d5d383aa");

static const QLatin1String
        notificationIndicationTestServiceUuid("bb137ac5-5716-4b80-873b-e2d11d29efe2");
static const QLatin1String
        notificationIndicationTestChar1Uuid("6da4d652-0248-478a-a5a8-1e2f076158cc");
static const QLatin1String
        notificationIndicationTestChar2Uuid("990930f0-b9cc-4c27-8c1b-ebc2bcae5c95");
static const QLatin1String
        notificationIndicationTestChar3Uuid("9a60486b-de5b-4e03-b914-4e158c0bd388");
static const QLatin1String
        notificationIndicationTestChar4Uuid("d92435d4-6c2e-43f8-a6be-bbb66b5a3e28");

static const QLatin1String connectionCountServiceUuid("78c61a07-a0f9-4b92-be2d-2570d8dbf010");
static const QLatin1String connectionCountCharUuid("9414ec2d-792f-46a2-a19e-186d0fb38a08");


#if defined(QT_ANDROID_BLUETOOTH) || defined(QT_WINRT_BLUETOOTH) || defined(Q_OS_DARWIN)
#define QT_BLUETOOTH_MTU_SUPPORTED
#endif

#if defined(QT_BLUETOOTH_MTU_SUPPORTED)
static const QLatin1String mtuServiceUuid("9a9483eb-cf4f-4c32-9a6b-794238d5b483");
static const QLatin1String mtuCharUuid("960d7e2a-a850-4a70-8064-cd74e9ccb6ff");
#endif

/*
 * This class contains all unit tests for QLowEnergyController
 * which require a remote device and can thus not run completely automated.
 *
 * This testcase acts as a bluetooth LE *client*.
 * The counterpart *server* device is the "bluetoothtestdevice" in the same
 * repository and it needs to be ran when this testcase is ran.
 *
 * The name of the server device needs to be adjusted in this code so that
 * this LE client can find it. For example on macOS and Linux it is a generic
 * "BluetoothTestDevice" where as on Android it is the device's bluetooth name
 * set by the user. Please see the BTLE_SERVER_DEVICE_NAME below.
 */
class tst_qlowenergycontroller_device : public QObject
{
    Q_OBJECT

public:
    tst_qlowenergycontroller_device();
    ~tst_qlowenergycontroller_device();
private slots:
    void initTestCase();
    void init();
    void cleanup();
    void cleanupTestCase();

    // Keep readServerPlatform as the first test, later tests
    // may depend on its results.
    void readServerPlatform();

#if defined(QT_BLUETOOTH_MTU_SUPPORTED)
    void checkMtuNegotiation();
#endif
    void readWriteLargeCharacteristic();
    void readDuringServiceDiscovery();
    void readNotificationAndIndicationProperty();
    void testNotificationAndIndication();

public:
    void checkconnectionCounter(std::unique_ptr<QLowEnergyController> &control);
    static int connectionCounter;

private:
    void discoverTestServer();

    std::unique_ptr<QBluetoothDeviceDiscoveryAgent> mDevAgent;
    std::unique_ptr<QLowEnergyController> mController;
    QBluetoothDeviceInfo mRemoteDeviceInfo;
    QString mServerDeviceName;
    QByteArray mServerPlatform;
};

// connectionCounter is used to check that the server-side connect events
// occur as expected. On the first time when the value is the initial "-1"
// we read the current connection count from a service/characteristic providing it.
// This way we don't need to always restart the server-side for testing
int tst_qlowenergycontroller_device::connectionCounter = -1;

tst_qlowenergycontroller_device::tst_qlowenergycontroller_device()
{
    QLoggingCategory::setFilterRules(QStringLiteral("qt.bluetooth* = true"));
}

tst_qlowenergycontroller_device::~tst_qlowenergycontroller_device() { }

void tst_qlowenergycontroller_device::initTestCase()
{
    qDebug() << "Testcase build time: " << __TIME__;
    mDevAgent.reset(new QBluetoothDeviceDiscoveryAgent(this));
    mDevAgent->setLowEnergyDiscoveryTimeout(75000);
    mServerDeviceName = qEnvironmentVariable("BTLE_SERVER_DEVICE_NAME");
    if (mServerDeviceName.isEmpty())
        mServerDeviceName = QStringLiteral("BluetoothTestDevice");
    qDebug() << "Using server device name for testing: " << mServerDeviceName;
    qDebug() << "To change this set BTLE_SERVER_DEVICE_NAME environment variable";
}

void tst_qlowenergycontroller_device::discoverTestServer()
{
    mRemoteDeviceInfo = QBluetoothDeviceInfo(); // Invalidate whatever we had before
    QSignalSpy finishedSpy(mDevAgent.get(), SIGNAL(finished()));
    QSignalSpy canceledSpy(mDevAgent.get(), SIGNAL(canceled()));
    // there should be no changes yet
    QVERIFY(finishedSpy.isValid() && finishedSpy.isEmpty());
    QVERIFY(canceledSpy.isValid() && canceledSpy.isEmpty());

    QObject forLifeTime;
    QObject::connect(mDevAgent.get(), &QBluetoothDeviceDiscoveryAgent::deviceDiscovered,
                     &forLifeTime, [&](const QBluetoothDeviceInfo& info) {
        if (info.name() == mServerDeviceName) {
            qDebug() << "Matching server device discovered, stopping device discovery agent";
            mDevAgent->stop();
        }
    });

    // Start device discovery
    mDevAgent->start(QBluetoothDeviceDiscoveryAgent::LowEnergyMethod);
    QTRY_VERIFY_WITH_TIMEOUT(finishedSpy.count() > 0 || canceledSpy.count() > 0, 80000);

    // Verify that we have found a matching server device
    bool deviceFound = false;
    const QList<QBluetoothDeviceInfo> infos = mDevAgent->discoveredDevices();
    for (const QBluetoothDeviceInfo &info : infos) {
        if (info.name() == mServerDeviceName) {
            mRemoteDeviceInfo = info;
            deviceFound = true;
            qDebug() << "Found a matching server device" << info.name() << info.address();
            break;
        }
        qDebug() << "Ignoring a non-matching device:" << info.name() << info.address();
    }
    QVERIFY2(deviceFound, "Cannot find remote device.");
}


void tst_qlowenergycontroller_device::init()
{
    // Connect to the test server. If unsuccessful, rediscover and retry.
    // Rediscovery may be needed as the address of the remote can change and
    // also at least Bluez backend recovers from its own internal errors
    // more likely making the test less flaky
    while (!mController || mController->state() != QLowEnergyController::ConnectedState) {
        discoverTestServer();
        QVERIFY(mRemoteDeviceInfo.isValid());
        mController.reset(QLowEnergyController::createCentral(mRemoteDeviceInfo));
        mController->connectToDevice();
        QTRY_VERIFY_WITH_TIMEOUT(mController->state() != QLowEnergyController::ConnectingState, 45000);
        if (mController->state() != QLowEnergyController::ConnectedState) {
            mController.reset();
            qDebug() << "Retrying connecting to the server in 5 seconds";
            QTest::qWait(5000);
        }
    }
    QCOMPARE(mController->state(), QLowEnergyController::ConnectedState);
    QCOMPARE(mController->error(), QLowEnergyController::NoError);
}

void tst_qlowenergycontroller_device::cleanup()
{
    mController->disconnectFromDevice();

    // Attempt a graceful close. If the test has already failed, the QTRY would exit immediately
    if (!QTest::currentTestFailed())
        QTRY_VERIFY_WITH_TIMEOUT(mController->state() ==
                                 QLowEnergyController::UnconnectedState, 30000);
    else
        QTest::qWait(2000);

    QCOMPARE(mController->state(), QLowEnergyController::UnconnectedState);
    qDebug() << "Disconnected from remote device, waiting 5s before deleting controller.";
    QTest::qWait(5000);
    mController.reset();
}

void tst_qlowenergycontroller_device::cleanupTestCase() { }

// The readServerPlatform should always be the first actual test function to execute.
// It reads a characteristic where the server reports on which platform it runs on.
// This information can then be used to adjust the test case's behavior accordingly;
// different platforms support slightly different things.
void tst_qlowenergycontroller_device::readServerPlatform()
{
    QVERIFY(mController->services().isEmpty());
    mController->discoverServices();
    QTRY_COMPARE(mController->state(), QLowEnergyController::DiscoveredState);
    QCOMPARE(mController->error(), QLowEnergyController::NoError);

    QSharedPointer<QLowEnergyService> service(
            mController->createServiceObject(QBluetoothUuid(platformIdentifierServiceUuid)));
    QVERIFY(service != nullptr);
    service->discoverDetails(QLowEnergyService::FullDiscovery);
    QTRY_COMPARE(service->state(), QLowEnergyService::ServiceState::RemoteServiceDiscovered);

    auto characteristic = service->characteristic(QBluetoothUuid(platformIdentifierCharUuid));
    mServerPlatform = characteristic.value();
    qDebug() << "Server reported its running on: " << mServerPlatform;
    QVERIFY(!mServerPlatform.isEmpty());
}


#if defined(QT_BLUETOOTH_MTU_SUPPORTED)
// Don't use QSKIP here as that
// would still cause lengthy init() and clean() executions.
void tst_qlowenergycontroller_device::checkMtuNegotiation()
{
    // service discovery, including MTU negotiation
    qDebug() << "Client-side MTU after connect" << mController->mtu();
#if ! defined(Q_OS_DARWIN)
    // The check below usually passes, but sometimes the BT stack gives a cached value
    // from a previous testcase run and the below fails => avoid flakiness
    QCOMPARE(mController->mtu(), 23);
#endif
    QVERIFY(mController->services().isEmpty());
    mController->discoverServices();
    QTRY_COMPARE(mController->state(), QLowEnergyController::DiscoveredState);
    QCOMPARE(mController->error(), QLowEnergyController::NoError);

    checkconnectionCounter(mController);

    // now a larger MTU should have been negotiated
    QTRY_VERIFY(mController->mtu() > 23);
    qDebug() << "MTU after service discovery" << mController->mtu();

    // check that central and peripheral agree on negotiated mtu
    QSharedPointer<QLowEnergyService> service(
            mController->createServiceObject(QBluetoothUuid(mtuServiceUuid)));
    QVERIFY(service != nullptr);
    service->discoverDetails(QLowEnergyService::FullDiscovery);
    QTRY_COMPARE(service->state(), QLowEnergyService::ServiceState::RemoteServiceDiscovered);

    auto characteristic = service->characteristic(QBluetoothUuid(mtuCharUuid));
    int mtu;
    memcpy(&mtu, characteristic.value().constData(), sizeof(int));
    qDebug() << "MTU reported by server-side:" << mtu;
    // Server-side mtu is not supported on all platforms
    if (mServerPlatform != "linux" && mServerPlatform != "darwin")
        QCOMPARE(mtu, mController->mtu());
}
#endif

#undef QT_BLUETOOTH_MTU_SUPPORTED

void tst_qlowenergycontroller_device::checkconnectionCounter(
        std::unique_ptr<QLowEnergyController> &mController)
{
    // on darwin the server-side connect/disconnect events are not reported reliably
    if (mServerPlatform == "darwin")
        return;
    QSharedPointer<QLowEnergyService> service(
            mController->createServiceObject(QBluetoothUuid(connectionCountServiceUuid)));
    QVERIFY(service != nullptr);
    service->discoverDetails(QLowEnergyService::FullDiscovery);
    QTRY_COMPARE(service->state(), QLowEnergyService::ServiceState::RemoteServiceDiscovered);

    auto counterCharacteristic = service->characteristic(QBluetoothUuid(connectionCountCharUuid));
    // If we have just started the test, read the current connection counter from the server.
    // The connection counter is essentially the number of "connected" events the server
    // has had.
    if (connectionCounter == -1) {
        memcpy(&connectionCounter, counterCharacteristic.value().constData(), sizeof(int));
        qDebug() << "Connection counter initialized from the server to:" << connectionCounter;
    } else {
        connectionCounter++;
        QByteArray value((const char *)&connectionCounter, sizeof(int));
        QCOMPARE(counterCharacteristic.value(), value);
    }
}

void tst_qlowenergycontroller_device::readWriteLargeCharacteristic()
{
    QVERIFY(mController->services().isEmpty());
    mController->discoverServices();
    QTRY_COMPARE(mController->state(), QLowEnergyController::DiscoveredState);

    checkconnectionCounter(mController);

    QSharedPointer<QLowEnergyService> service(
            mController->createServiceObject(QBluetoothUuid(largeCharacteristicServiceUuid)));
    QVERIFY(service != nullptr);
    service->discoverDetails(QLowEnergyService::SkipValueDiscovery);
    QTRY_COMPARE(service->state(), QLowEnergyService::ServiceState::RemoteServiceDiscovered);

    QSignalSpy readSpy(service.get(), &QLowEnergyService::characteristicRead);
    QSignalSpy writtenSpy(service.get(), &QLowEnergyService::characteristicWritten);
    QCOMPARE(readSpy.count(), 0);
    QCOMPARE(writtenSpy.count(), 0);

    // The service discovery skipped the values => check that the default value is all zeroes
    auto characteristic = service->characteristic(QBluetoothUuid(largeCharacteristicCharUuid));
    QByteArray testArray(0);
    qDebug() << "Initial large characteristic value:" << characteristic.value();
    QCOMPARE(characteristic.value(), testArray);

    // Read the characteristic value and verify it is the one the server-side sets (0x0b 0x00 ..)
    service->readCharacteristic(characteristic);
    QTRY_COMPARE(readSpy.count(), 1);
    qDebug() << "Large characteristic value after read:" << characteristic.value();
    testArray = QByteArray(512, 0);
    testArray[0] = 0x0b;
    QCOMPARE(characteristic.value(), testArray);

    // Write a new value to characteristic and read it back
    for (int i = 0; i < 512; ++i) {
        testArray[i] = i % 5;
    }
    service->writeCharacteristic(characteristic, testArray);
    QCOMPARE(service->error(), QLowEnergyService::ServiceError::NoError);
    QTRY_COMPARE(writtenSpy.count(), 1);

    service->readCharacteristic(characteristic);
    QTRY_COMPARE(readSpy.count(), 2);
    qDebug() << "Large characteristic value after write/read:" << characteristic.value();
    QCOMPARE(characteristic.value(), testArray);
}

void tst_qlowenergycontroller_device::readDuringServiceDiscovery()
{
    QVERIFY(mController->services().isEmpty());
    mController->discoverServices();
    QTRY_COMPARE(mController->state(), QLowEnergyController::DiscoveredState);

    checkconnectionCounter(mController);

    QSharedPointer<QLowEnergyService> service(
            mController->createServiceObject(QBluetoothUuid(largeCharacteristicServiceUuid)));
    QVERIFY(service != nullptr);
    service->discoverDetails(QLowEnergyService::FullDiscovery);
    QTRY_COMPARE(service->state(), QLowEnergyService::ServiceState::RemoteServiceDiscovered);

    QSignalSpy readSpy(service.get(), &QLowEnergyService::characteristicRead);
    QSignalSpy writtenSpy(service.get(), &QLowEnergyService::characteristicWritten);
    QCOMPARE(readSpy.count(), 0);
    QCOMPARE(writtenSpy.count(), 0);

    // Value that is initially set on the characteristic at the server-side (0x0b 0x00 ..)
    QByteArray testArray(512, 0);
    testArray[0] = 0x0b;

    // We did a full service discovery and should have an initial value to compare
    auto characteristic = service->characteristic(QBluetoothUuid(largeCharacteristicCharUuid));
    QByteArray valueFromServiceDiscovery = characteristic.value();
    qDebug() << "Large characteristic value from service discovery:" << valueFromServiceDiscovery;
    // On darwin the server does not restart (disconnect) in-between the case runs
    // and the initial value may be from a previous test function
    if (mServerPlatform != "darwin")
        QCOMPARE(characteristic.value(), testArray);

    // Check that the value from service discovery and explicit characteristic read match
    service->readCharacteristic(characteristic);
    QTRY_COMPARE(readSpy.count(), 1);
    qDebug() << "Large characteristic value after read:" << characteristic.value();
    QCOMPARE(characteristic.value(), valueFromServiceDiscovery);

    // Write a new value to the characteristic and read it back
    for (int i = 0; i < 512; ++i) {
        testArray[i] = i % 5;
    }
    service->writeCharacteristic(characteristic, testArray);
    QCOMPARE(service->error(), QLowEnergyService::ServiceError::NoError);
    QTRY_COMPARE(writtenSpy.count(), 1);

    service->readCharacteristic(characteristic);
    QTRY_COMPARE(readSpy.count(), 2);
    qDebug() << "Large characteristic value after write/read:" << characteristic.value();
    QCOMPARE(characteristic.value(), testArray);
}

void tst_qlowenergycontroller_device::readNotificationAndIndicationProperty()
{
    // discover services
    QVERIFY(mController->services().isEmpty());
    mController->discoverServices();
    QTRY_COMPARE(mController->state(), QLowEnergyController::DiscoveredState);

    checkconnectionCounter(mController);

    // check test service is available
    QVERIFY(mController->services().contains(QBluetoothUuid(notificationIndicationTestServiceUuid)));

    // get service object
    QSharedPointer<QLowEnergyService> service(mController->createServiceObject(
            QBluetoothUuid(notificationIndicationTestServiceUuid)));
    QVERIFY(service != nullptr);
    service->discoverDetails(QLowEnergyService::FullDiscovery);
    QTRY_COMPARE(service->state(), QLowEnergyService::ServiceState::RemoteServiceDiscovered);

    // check that all four characteristics are found
    QCOMPARE(service->characteristics().size(), 4);

    // check that properties are correctly set
    auto notifyOrIndicate = QLowEnergyCharacteristic::PropertyType::Notify
            | QLowEnergyCharacteristic::PropertyType::Indicate;
    {
        QLowEnergyCharacteristic characteristic =
                service->characteristic(QBluetoothUuid(notificationIndicationTestChar1Uuid));
        QCOMPARE(characteristic.properties() & notifyOrIndicate, 0);
    }
    {
        QLowEnergyCharacteristic characteristic =
                service->characteristic(QBluetoothUuid(notificationIndicationTestChar2Uuid));
        QCOMPARE(characteristic.properties() & notifyOrIndicate,
                 QLowEnergyCharacteristic::PropertyType::Notify);
    }
    {
        QLowEnergyCharacteristic characteristic =
                service->characteristic(QBluetoothUuid(notificationIndicationTestChar3Uuid));
        QCOMPARE(characteristic.properties() & notifyOrIndicate,
                 QLowEnergyCharacteristic::PropertyType::Indicate);
    }
    {
        QLowEnergyCharacteristic characteristic =
                service->characteristic(QBluetoothUuid(notificationIndicationTestChar4Uuid));
        QCOMPARE(characteristic.properties() & notifyOrIndicate, notifyOrIndicate);
    }
}

void tst_qlowenergycontroller_device::testNotificationAndIndication()
{
    // discover services
    QVERIFY(mController->services().isEmpty());
    mController->discoverServices();
    QTRY_COMPARE(mController->state(), QLowEnergyController::DiscoveredState);

    checkconnectionCounter(mController);

    // get service object
    QSharedPointer<QLowEnergyService> service(mController->createServiceObject(
            QBluetoothUuid(notificationIndicationTestServiceUuid)));
    QVERIFY(service != nullptr);
    service->discoverDetails(QLowEnergyService::FullDiscovery);
    QTRY_COMPARE(service->state(), QLowEnergyService::ServiceState::RemoteServiceDiscovered);

    // Verify that notification works
    {
        QLowEnergyCharacteristic characteristic =
                service->characteristic(QBluetoothUuid(notificationIndicationTestChar2Uuid));
        auto notifyOrIndicate = QLowEnergyCharacteristic::PropertyType::Notify
                | QLowEnergyCharacteristic::PropertyType::Indicate;
        QCOMPARE(characteristic.properties() & notifyOrIndicate,
                 QLowEnergyCharacteristic::PropertyType::Notify);

        // getting cccd
        QLowEnergyDescriptor cccd = characteristic.clientCharacteristicConfiguration();
        QVERIFY(cccd.isValid());

        // write to cccd
        bool cccdWritten = false;
        QObject dummy; // for lifetime management
        QObject::connect(
                service.get(), &QLowEnergyService::descriptorWritten, &dummy,
                [&cccdWritten](const QLowEnergyDescriptor &info, const QByteArray &) {
                    if (info.uuid()
                        == QBluetoothUuid::DescriptorType::ClientCharacteristicConfiguration) {
                        cccdWritten = true;
                    }
                });
        service->writeDescriptor(cccd, QLowEnergyCharacteristic::CCCDEnableNotification);
        QTRY_VERIFY(cccdWritten);

        // notification should be enabled
        auto oldvalue = characteristic.value();
        QCOMPARE(characteristic.value(), oldvalue);
        // wait for change
        QTRY_VERIFY(characteristic.value() != oldvalue);
        // wait again
        oldvalue = characteristic.value();
        QCOMPARE(characteristic.value(), oldvalue);
        // wait for change
        QTRY_VERIFY(characteristic.value() != oldvalue);

        // disable notification
        cccdWritten = false;
        service->writeDescriptor(cccd, QLowEnergyCharacteristic::CCCDDisable);
        QTRY_VERIFY(cccdWritten);

        // wait for a moment in case there is a value change just happening,
        // then check that there are no more notifications:
        QTest::qWait(200);
        oldvalue = characteristic.value();
        for (int i = 0; i < 3; ++i) {
            QTest::qWait(100);
            QCOMPARE(characteristic.value(), oldvalue);
        }
    }

    // Verify that indication works
    {
        QLowEnergyCharacteristic characteristic =
                service->characteristic(QBluetoothUuid(notificationIndicationTestChar3Uuid));
        auto notifyOrIndicate = QLowEnergyCharacteristic::PropertyType::Notify
                | QLowEnergyCharacteristic::PropertyType::Indicate;
        QCOMPARE(characteristic.properties() & notifyOrIndicate,
                 QLowEnergyCharacteristic::PropertyType::Indicate);

        // getting cccd
        QLowEnergyDescriptor cccd = characteristic.clientCharacteristicConfiguration();
        QVERIFY(cccd.isValid());

        // write to cccd
        bool cccdWritten = false;
        QObject dummy; // for lifetime management
        QObject::connect(
                service.get(), &QLowEnergyService::descriptorWritten, &dummy,
                [&cccdWritten](const QLowEnergyDescriptor &info, const QByteArray &) {
                    if (info.uuid()
                        == QBluetoothUuid::DescriptorType::ClientCharacteristicConfiguration) {
                        cccdWritten = true;
                    }
                });
        QByteArray newValue = QByteArray::fromHex("0200");
        service->writeDescriptor(cccd, newValue);
        QTRY_VERIFY(cccdWritten);

        // indication should be enabled
        auto oldvalue = characteristic.value();
        QCOMPARE(characteristic.value(), oldvalue);
        // wait for change
        QTRY_VERIFY(characteristic.value() != oldvalue);
        // wait again
        oldvalue = characteristic.value();
        QCOMPARE(characteristic.value(), oldvalue);
        // wait for change
        QTRY_VERIFY(characteristic.value() != oldvalue);

        // disable indication
        cccdWritten = false;
        newValue = QByteArray::fromHex("0000");
        service->writeDescriptor(cccd, newValue);
        QTRY_VERIFY(cccdWritten);

        // wait for a moment in case there is a value change just happening,
        // then check that there are no more notifications:
        QTest::qWait(200);
        oldvalue = characteristic.value();
        for (int i = 0; i < 3; ++i) {
            QTest::qWait(100);
            QCOMPARE(characteristic.value(), oldvalue);
        }
    }

    // indication and notification works
#if defined(Q_OS_LINUX)
    // If the client (this testcase) is linux and the characteristic has both
    // NTF & IND supported, the Bluez stack will try to enable both NTF & IND
    // at the same time regardless of what we write to CCCD. Darwin server will
    // reject this as an error (ATT error 0xf5, which is a reserved error)
    if (mServerPlatform != "darwin")
#endif
    {
        QLowEnergyCharacteristic characteristic =
                service->characteristic(QBluetoothUuid(notificationIndicationTestChar4Uuid));
        auto notifyOrIndicate = QLowEnergyCharacteristic::PropertyType::Notify
                | QLowEnergyCharacteristic::PropertyType::Indicate;
        QCOMPARE(characteristic.properties() & notifyOrIndicate, notifyOrIndicate);

        // getting cccd
        QLowEnergyDescriptor cccd = characteristic.clientCharacteristicConfiguration();
        QVERIFY(cccd.isValid());

        // write to cccd
        bool cccdWritten = false;
        QObject dummy; // for lifetime management
        QObject::connect(
                service.get(), &QLowEnergyService::descriptorWritten, &dummy,
                [&cccdWritten](const QLowEnergyDescriptor &info, const QByteArray &) {
                    if (info.uuid()
                        == QBluetoothUuid::DescriptorType::ClientCharacteristicConfiguration) {
                        cccdWritten = true;
                    }
                });
        QByteArray newValue = QByteArray::fromHex("0100");
        service->writeDescriptor(cccd, newValue);
        QTRY_VERIFY(cccdWritten);

        // notification should be enabled
        auto oldvalue = characteristic.value();
        QCOMPARE(characteristic.value(), oldvalue);
        // wait for change
        QTRY_VERIFY(characteristic.value() != oldvalue);
        // wait again
        oldvalue = characteristic.value();
        QCOMPARE(characteristic.value(), oldvalue);
        // wait for change
        QTRY_VERIFY(characteristic.value() != oldvalue);

        // disable notification
        cccdWritten = false;
        newValue = QByteArray::fromHex("0000");
        service->writeDescriptor(cccd, newValue);
        QTRY_VERIFY(cccdWritten);

        // check that there are no updates:
        oldvalue = characteristic.value();
        for (int i = 0; i < 3; ++i) {
            QTest::qWait(100);
            QCOMPARE(characteristic.value(), oldvalue);
        }

        newValue = QByteArray::fromHex("0200");
        service->writeDescriptor(cccd, newValue);
        QTRY_VERIFY(cccdWritten);

        // indication should be enabled
        oldvalue = characteristic.value();
        QCOMPARE(characteristic.value(), oldvalue);
        // wait for change
        QTRY_VERIFY(characteristic.value() != oldvalue);
        // wait again
        oldvalue = characteristic.value();
        QCOMPARE(characteristic.value(), oldvalue);
        // wait for change
        QTRY_VERIFY(characteristic.value() != oldvalue);

        // disable indication
        cccdWritten = false;
        newValue = QByteArray::fromHex("0000");
        service->writeDescriptor(cccd, newValue);
        QTRY_VERIFY(cccdWritten);

        // check that there are no indications:
        oldvalue = characteristic.value();
        for (int i = 0; i < 3; ++i) {
            QTest::qWait(100);
            QCOMPARE(characteristic.value(), oldvalue);
        }
    }
}

QTEST_MAIN(tst_qlowenergycontroller_device)

#include "tst_qlowenergycontroller_device.moc"