summaryrefslogtreecommitdiffstats
path: root/src/bluetooth/qbluetoothdevicediscoveryagent.cpp
blob: c9c3fa3937589396427c2fb90129d309e98cafb1 (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
/****************************************************************************
**
** Copyright (C) 2016 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:LGPL$
** 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 Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 3 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL3 included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 3 requirements
** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 2.0 or (at your option) the GNU General
** Public license version 3 or any later version approved by the KDE Free
** Qt Foundation. The licenses are as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
** 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-2.0.html and
** https://www.gnu.org/licenses/gpl-3.0.html.
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "qbluetoothhostinfo.h"

#include "qbluetoothdevicediscoveryagent.h"
#include "qbluetoothdevicediscoveryagent_p.h"
#include <QtCore/qloggingcategory.h>

QT_BEGIN_NAMESPACE

Q_DECLARE_LOGGING_CATEGORY(QT_BT)

/*!
    \class QBluetoothDeviceDiscoveryAgent
    \inmodule QtBluetooth
    \brief The QBluetoothDeviceDiscoveryAgent class discovers the Bluetooth
    devices nearby.

    \since 5.2

    To discover the nearby Bluetooth devices:
    \list
    \li create an instance of QBluetoothDeviceDiscoveryAgent,
    \li connect to either the deviceDiscovered() or finished() signals,
    \li and call start().
    \endlist

    \snippet doc_src_qtbluetooth.cpp device_discovery

    To retrieve results asynchronously, connect to the deviceDiscovered() signal. To get a list of
    all discovered devices, call discoveredDevices() after the finished() signal.

    This class can be used to discover Classic and Low Energy Bluetooth devices.
    The individual device type can be determined via the
    \l QBluetoothDeviceInfo::coreConfigurations() attribute.
    In most cases the list returned by \l discoveredDevices() contains both types
    of devices. However not every platform can detect both types of devices.
    On platforms with this limitation (for example iOS only suports Low Energy discovery),
    the discovery process will limit the search to the type which is supported.

    \note Since Android 6.0 the ability to detect devices requires ACCESS_COARSE_LOCATION.
*/

/*!
    \enum QBluetoothDeviceDiscoveryAgent::Error

    Indicates all possible error conditions found during Bluetooth device discovery.

    \value NoError          No error has occurred.
    \value PoweredOffError  The Bluetooth adaptor is powered off, power it on before doing discovery.
    \value InputOutputError    Writing or reading from the device resulted in an error.
    \value InvalidBluetoothAdapterError The passed local adapter address does not match the physical
                                        adapter address of any local Bluetooth device.
    \value UnsupportedPlatformError Device discovery is not possible or implemented on the current
                                    platform. The error is set in response to a call to \l start().
                                    An example for such cases are iOS versions below 5.0 which do not support
                                    Bluetooth device search at all. This value was introduced by Qt 5.5.
    \value UnsupportedDiscoveryMethod   One of the requested discovery methods is not supported by
                                        the current platform. This value was introduced by Qt 5.8.
    \value UnknownError     An unknown error has occurred.
*/

/*!
    \enum QBluetoothDeviceDiscoveryAgent::InquiryType

    This enum describes the inquiry type used while discovering Bluetooth devices.

    \value GeneralUnlimitedInquiry  A general unlimited inquiry. Discovers all visible Bluetooth
                                    devices in the local vicinity.
    \value LimitedInquiry           A limited inquiry discovers devices that are in limited
                                    inquiry mode.

    LimitedInquiry is not supported on all platforms. If it is requested on a platform that does not
    support it, GeneralUnlimitedInquiry will be used instead. Setting LimitedInquiry is useful
    for multi-player Bluetooth-based games that needs faster communication between the devices.
    The phone scans for devices in LimitedInquiry and Service Discovery is done on one or two devices
    to speed up the service scan. After the game has connected to the device it intended to,
    the device returns to GeneralUnlimitedInquiry.
*/

/*!
    \enum QBluetoothDeviceDiscoveryAgent::DiscoveryMethod

    This enum descibes the type of discovery method employed by the QBluetoothDeviceDiscoveryAgent.

    \value NoMethod             The discovery is not possible. None of the available
                                methods are supported.
    \value ClassicMethod        The discovery process searches for Bluetooth Classic
                                (BaseRate) devices.
    \value LowEnergyMethod      The discovery process searches for Bluetooth Low Energy
                                devices.

    \sa supportedDiscoveryMethods()
    \since 5.8
*/

/*!
    \fn void QBluetoothDeviceDiscoveryAgent::deviceDiscovered(const QBluetoothDeviceInfo &info)

    This signal is emitted when the Bluetooth device described by \a info is discovered.

    The signal is emitted as soon as the most important device information
    has been collected. However, as long as the \l finished() signal has not
    been emitted the information collection continues even for already discovered
    devices. This is particularly true for signal strength information (RSSI) and
    manufacturer data updates. If the use case requires continuous manufacturer data
    or RSSI updates it is advisable to retrieve the device information via
    \l discoveredDevices() once the discovery has finished or listen to the
    \l deviceUpdated() signal.

    If \l lowEnergyDiscoveryTimeout() is larger than 0 the signal is only ever
    emitted when at least one attribute of \a info changes. This reflects the desire to
    receive updates as more precise information becomes available. The exception to this
    behavior is the case when \l lowEnergyDiscoveryTimeout is set to \c 0. A timeout of \c 0
    expresses the desire to monitor the appearance and disappearance of Low Energy devices
    over time. Under this condition the \l deviceDiscovered() signal is emitted even if
    \a info has not changed since the last signal emission.

    \sa QBluetoothDeviceInfo::rssi(), lowEnergyDiscoveryTimeout()
*/

/*!
    \fn void QBluetoothDeviceDiscoveryAgent::deviceUpdated(const QBluetoothDeviceInfo &info, QBluetoothDeviceInfo::Fields updatedFields)

    This signal is emitted when the agent receives additional information about
    the Bluetooth device described by \a info. The \a updatedFields flags tell
    which information has been updated.

    During discovery, some information can change dynamically, such as
    \l {QBluetoothDeviceInfo::rssi()}{signal strength} and
    \l {QBluetoothDeviceInfo::manufacturerData()}{manufacturerData}.
    This signal informs you that if your application is displaying this data, it
    can be updated, rather than waiting until the discovery has finished.

    \note This signal is only emitted on Android and BlueZ 5.x.

    \sa QBluetoothDeviceInfo::rssi(), lowEnergyDiscoveryTimeout()
*/

// TODO deviceUpdated() signal not implemented on WinRT and Apple platforms

/*!
    \fn void QBluetoothDeviceDiscoveryAgent::finished()

    This signal is emitted when Bluetooth device discovery completes.
    The signal is not going to be emitted if the device discovery finishes with an error.
*/

/*!
    \fn void QBluetoothDeviceDiscoveryAgent::error(QBluetoothDeviceDiscoveryAgent::Error error)

    This signal is emitted when an \a error occurs during Bluetooth device discovery.
    The \a error parameter describes the error that occurred.

    \sa error(), errorString()
*/

/*!
    \fn void QBluetoothDeviceDiscoveryAgent::canceled()

    This signal is emitted when device discovery is aborted by a call to stop().
*/

/*!
    \fn bool QBluetoothDeviceDiscoveryAgent::isActive() const

    Returns true if the agent is currently discovering Bluetooth devices, otherwise returns false.
*/

/*!
    Constructs a new Bluetooth device discovery agent with parent \a parent.
*/
QBluetoothDeviceDiscoveryAgent::QBluetoothDeviceDiscoveryAgent(QObject *parent) :
    QObject(parent),
    d_ptr(new QBluetoothDeviceDiscoveryAgentPrivate(QBluetoothAddress(), this))
{
}

/*!
    Constructs a new Bluetooth device discovery agent with \a parent.

    It uses \a deviceAdapter for the device search. If \a deviceAdapter is default constructed the resulting
    QBluetoothDeviceDiscoveryAgent object will use the local default Bluetooth adapter.

    If a \a deviceAdapter is specified that is not a local adapter \l error() will be set to
    \l InvalidBluetoothAdapterError. Therefore it is recommended to test the error flag immediately after
    using this constructor.

    \sa error()
*/
QBluetoothDeviceDiscoveryAgent::QBluetoothDeviceDiscoveryAgent(
    const QBluetoothAddress &deviceAdapter, QObject *parent) :
    QObject(parent),
    d_ptr(new QBluetoothDeviceDiscoveryAgentPrivate(deviceAdapter, this))
{
    if (!deviceAdapter.isNull()) {
        const QList<QBluetoothHostInfo> localDevices = QBluetoothLocalDevice::allDevices();
        for (const QBluetoothHostInfo &hostInfo : localDevices) {
            if (hostInfo.address() == deviceAdapter)
                return;
        }
        d_ptr->lastError = InvalidBluetoothAdapterError;
        d_ptr->errorString = tr("Invalid Bluetooth adapter address");
    }
}

/*!
  Destructor for ~QBluetoothDeviceDiscoveryAgent()
*/
QBluetoothDeviceDiscoveryAgent::~QBluetoothDeviceDiscoveryAgent()
{
    delete d_ptr;
}

/*!
    \property QBluetoothDeviceDiscoveryAgent::inquiryType
    \brief type of inquiry scan to be used while discovering devices

    This property affects the type of inquiry scan which is performed while discovering devices.

    By default, this property is set to GeneralUnlimitedInquiry.

    Not all platforms support LimitedInquiry.

    \sa InquiryType
*/
QBluetoothDeviceDiscoveryAgent::InquiryType QBluetoothDeviceDiscoveryAgent::inquiryType() const
{
    Q_D(const QBluetoothDeviceDiscoveryAgent);
    return d->inquiryType;
}

void QBluetoothDeviceDiscoveryAgent::setInquiryType(QBluetoothDeviceDiscoveryAgent::InquiryType type)
{
    Q_D(QBluetoothDeviceDiscoveryAgent);
    d->inquiryType = type;
}

/*!
    Returns a list of all discovered Bluetooth devices.
*/
QList<QBluetoothDeviceInfo> QBluetoothDeviceDiscoveryAgent::discoveredDevices() const
{
    Q_D(const QBluetoothDeviceDiscoveryAgent);
    return d->discoveredDevices;
}

/*!
    Sets the maximum search time for Bluetooth Low Energy device search to
    \a timeout in milliseconds. If \a timeout is \c 0 the discovery runs
    until \l stop() is called.

    This reflects the fact that the discovery process for Bluetooth Low Energy devices
    is mostly open ended. The platform continues to look for more devices until the search is
    manually stopped. The timeout ensures that the search is aborted after \a timeout milliseconds.
    Of course, it is still possible to manually abort the discovery by calling \l stop().

    The new timeout value does not take effect until the device search is restarted.
    In addition the timeout does not affect the classic Bluetooth device search. Depending on
    the platform the classic search may add more time to the total discovery process
    beyond \a timeout.

    \sa lowEnergyDiscoveryTimeout()
    \since 5.8
 */
void QBluetoothDeviceDiscoveryAgent::setLowEnergyDiscoveryTimeout(int timeout)
{
    Q_D(QBluetoothDeviceDiscoveryAgent);

    // cannot deliberately turn it off
    if (d->lowEnergySearchTimeout < 0 || timeout < 0) {
        qCDebug(QT_BT) << "The Bluetooth Low Energy device discovery timeout cannot be negative "
                          "or set on a backend which does not support this feature.";
        return;
    }

    d->lowEnergySearchTimeout = timeout;
}

/*!
    Returns a timeout in milliseconds that is applied to the Bluetooth Low Energy device search.
    A value of \c -1 implies that the platform does not support this property and the timeout for
    the device search cannot be adjusted. A return value of \c 0
    implies a never-ending search which must be manually stopped via \l stop().

    \sa setLowEnergyDiscoveryTimeout()
    \since 5.8
 */
int QBluetoothDeviceDiscoveryAgent::lowEnergyDiscoveryTimeout() const
{
    Q_D(const QBluetoothDeviceDiscoveryAgent);
    return d->lowEnergySearchTimeout;
}

/*!
    \fn QBluetoothDeviceDiscoveryAgent::DiscoveryMethods QBluetoothDeviceDiscoveryAgent::supportedDiscoveryMethods()

    This function returns the discovery methods supported by the current platform.
    It can be used to limit the scope of the device discovery.

    \since 5.8
*/

/*!
    Starts Bluetooth device discovery, if it is not already started.

    The deviceDiscovered() signal is emitted as each device is discovered. The finished() signal
    is emitted once device discovery is complete. The discovery utilizes the maximum set of
    supported discovery methods on the platform.

    \sa supportedDiscoveryMethods()
*/
void QBluetoothDeviceDiscoveryAgent::start()
{
    Q_D(QBluetoothDeviceDiscoveryAgent);
    if (!isActive() && d->lastError != InvalidBluetoothAdapterError)
        d->start(supportedDiscoveryMethods());
}

/*!
    Starts Bluetooth device discovery, if it is not already started and the provided
    \a methods are supported.
    The discovery \a methods limit the scope of the device search.
    For example, if the target service or device is a Bluetooth Low Energy device,
    this function could be used to limit the search to Bluetooth Low Energy devices and
    thereby reduces the discovery time significantly.

    \note \a methods only determines the type of discovery and does not imply
    the filtering of the results. For example, the search may still contain classic bluetooth devices
    despite \a methods being set to \l {QBluetoothDeviceDiscoveryAgent::LowEnergyMethod}
    {LowEnergyMethod} only. This may happen due to previously cached search results
    which may be incorporated into the search results.

    \since 5.8
*/
void QBluetoothDeviceDiscoveryAgent::start(DiscoveryMethods methods)
{
    if (methods == NoMethod)
        return;

    DiscoveryMethods supported =
            QBluetoothDeviceDiscoveryAgent::supportedDiscoveryMethods();

    Q_D(QBluetoothDeviceDiscoveryAgent);
    if (!((supported & methods) == methods)) {
        d->lastError = UnsupportedDiscoveryMethod;
        d->errorString = QBluetoothDeviceDiscoveryAgent::tr("One or more device discovery methods "
                                                            "are not supported on this platform");
        emit error(d->lastError);
        return;
    }

    if (!isActive() && d->lastError != InvalidBluetoothAdapterError)
        d->start(methods);
}

/*!
    Stops Bluetooth device discovery.  The cancel() signal is emitted once the
    device discovery is canceled.  start() maybe called before the cancel signal is
    received.  Once start() has been called the cancel signal from the prior
    discovery will be discarded.
*/
void QBluetoothDeviceDiscoveryAgent::stop()
{
    Q_D(QBluetoothDeviceDiscoveryAgent);
    if (isActive() && d->lastError != InvalidBluetoothAdapterError)
        d->stop();
}

bool QBluetoothDeviceDiscoveryAgent::isActive() const
{
    Q_D(const QBluetoothDeviceDiscoveryAgent);
    return d->isActive();
}

/*!
    Returns the last error.
*/
QBluetoothDeviceDiscoveryAgent::Error QBluetoothDeviceDiscoveryAgent::error() const
{
    Q_D(const QBluetoothDeviceDiscoveryAgent);

    return d->lastError;
}

/*!
    Returns a human-readable description of the last error.
*/
QString QBluetoothDeviceDiscoveryAgent::errorString() const
{
    Q_D(const QBluetoothDeviceDiscoveryAgent);
    return d->errorString;
}

#include "moc_qbluetoothdevicediscoveryagent.cpp"

QT_END_NAMESPACE