Warning: That file was not part of the compilation database. It may have many parsing errors.

1/****************************************************************************
2**
3** Copyright (C) 2016 Lauri Laanmets (Proekspert AS) <lauri.laanmets@eesti.ee>
4** Copyright (C) 2016 The Qt Company Ltd.
5** Contact: https://www.qt.io/licensing/
6**
7** This file is part of the QtBluetooth module of the Qt Toolkit.
8**
9** $QT_BEGIN_LICENSE:LGPL$
10** Commercial License Usage
11** Licensees holding valid commercial Qt licenses may use this file in
12** accordance with the commercial license agreement provided with the
13** Software or, alternatively, in accordance with the terms contained in
14** a written agreement between you and The Qt Company. For licensing terms
15** and conditions see https://www.qt.io/terms-conditions. For further
16** information use the contact form at https://www.qt.io/contact-us.
17**
18** GNU Lesser General Public License Usage
19** Alternatively, this file may be used under the terms of the GNU Lesser
20** General Public License version 3 as published by the Free Software
21** Foundation and appearing in the file LICENSE.LGPL3 included in the
22** packaging of this file. Please review the following information to
23** ensure the GNU Lesser General Public License version 3 requirements
24** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
25**
26** GNU General Public License Usage
27** Alternatively, this file may be used under the terms of the GNU
28** General Public License version 2.0 or (at your option) the GNU General
29** Public license version 3 or any later version approved by the KDE Free
30** Qt Foundation. The licenses are as published by the Free Software
31** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
32** included in the packaging of this file. Please review the following
33** information to ensure the GNU General Public License requirements will
34** be met: https://www.gnu.org/licenses/gpl-2.0.html and
35** https://www.gnu.org/licenses/gpl-3.0.html.
36**
37** $QT_END_LICENSE$
38**
39****************************************************************************/
40
41#include "qbluetoothdevicediscoveryagent_p.h"
42#include <QtCore/QLoggingCategory>
43#include <QtBluetooth/QBluetoothAddress>
44#include <QtBluetooth/QBluetoothDeviceInfo>
45#include <QtCore/private/qjnihelpers_p.h>
46#include "android/devicediscoverybroadcastreceiver_p.h"
47#include <QtAndroidExtras/QAndroidJniEnvironment>
48#include <QtAndroid>
49
50QT_BEGIN_NAMESPACE
51
52Q_DECLARE_LOGGING_CATEGORY(QT_BT_ANDROID)
53
54enum {
55 NoScanActive = 0,
56 SDPScanActive = 1,
57 BtleScanActive = 2
58};
59
60QBluetoothDeviceDiscoveryAgentPrivate::QBluetoothDeviceDiscoveryAgentPrivate(
61 const QBluetoothAddress &deviceAdapter, QBluetoothDeviceDiscoveryAgent *parent) :
62 inquiryType(QBluetoothDeviceDiscoveryAgent::GeneralUnlimitedInquiry),
63 lastError(QBluetoothDeviceDiscoveryAgent::NoError),
64 receiver(0),
65 m_adapterAddress(deviceAdapter),
66 m_active(NoScanActive),
67 leScanTimeout(0),
68 pendingCancel(false),
69 pendingStart(false),
70 lowEnergySearchTimeout(25000),
71 q_ptr(parent)
72{
73 QAndroidJniEnvironment env;
74 adapter = QAndroidJniObject::callStaticObjectMethod("android/bluetooth/BluetoothAdapter",
75 "getDefaultAdapter",
76 "()Landroid/bluetooth/BluetoothAdapter;");
77 if (!adapter.isValid()) {
78 if (env->ExceptionCheck()) {
79 env->ExceptionDescribe();
80 env->ExceptionClear();
81 }
82 qCWarning(QT_BT_ANDROID) << "Device does not support Bluetooth";
83 }
84}
85
86QBluetoothDeviceDiscoveryAgentPrivate::~QBluetoothDeviceDiscoveryAgentPrivate()
87{
88 if (m_active != NoScanActive)
89 stop();
90
91 if (leScanner.isValid())
92 leScanner.setField<jlong>("qtObject", reinterpret_cast<jlong>(nullptr));
93
94 if (receiver) {
95 receiver->unregisterReceiver();
96 delete receiver;
97 }
98}
99
100bool QBluetoothDeviceDiscoveryAgentPrivate::isActive() const
101{
102 if (pendingStart)
103 return true;
104 if (pendingCancel)
105 return false;
106 return m_active != NoScanActive;
107}
108
109QBluetoothDeviceDiscoveryAgent::DiscoveryMethods QBluetoothDeviceDiscoveryAgent::supportedDiscoveryMethods()
110{
111 return (LowEnergyMethod | ClassicMethod);
112}
113
114void QBluetoothDeviceDiscoveryAgentPrivate::start(QBluetoothDeviceDiscoveryAgent::DiscoveryMethods methods)
115{
116 //TODO Implement discovery method handling (see input parameter)
117 requestedMethods = methods;
118
119 if (pendingCancel) {
120 pendingStart = true;
121 return;
122 }
123
124 Q_Q(QBluetoothDeviceDiscoveryAgent);
125
126 if (!adapter.isValid()) {
127 qCWarning(QT_BT_ANDROID) << "Device does not support Bluetooth";
128 lastError = QBluetoothDeviceDiscoveryAgent::InputOutputError;
129 errorString = QBluetoothDeviceDiscoveryAgent::tr("Device does not support Bluetooth");
130 emit q->error(lastError);
131 return;
132 }
133
134 if (!m_adapterAddress.isNull()
135 && adapter.callObjectMethod<jstring>("getAddress").toString()
136 != m_adapterAddress.toString()) {
137 qCWarning(QT_BT_ANDROID) << "Incorrect local adapter passed.";
138 lastError = QBluetoothDeviceDiscoveryAgent::InvalidBluetoothAdapterError;
139 errorString = QBluetoothDeviceDiscoveryAgent::tr("Passed address is not a local device.");
140 emit q->error(lastError);
141 return;
142 }
143
144 const int state = adapter.callMethod<jint>("getState");
145 if (state != 12) { // BluetoothAdapter.STATE_ON
146 lastError = QBluetoothDeviceDiscoveryAgent::PoweredOffError;
147 errorString = QBluetoothDeviceDiscoveryAgent::tr("Device is powered off");
148 emit q->error(lastError);
149 return;
150 }
151
152 // check Android v23+ permissions
153 // -> BTLE search requires android.permission.ACCESS_COARSE_LOCATION or android.permission.ACCESS_FINE_LOCATION
154 if (requestedMethods & QBluetoothDeviceDiscoveryAgent::LowEnergyMethod
155 && QtAndroid::androidSdkVersion() >= 23)
156 {
157 const QString coarsePermission(QLatin1String("android.permission.ACCESS_COARSE_LOCATION"));
158 const QString finePermission(QLatin1String("android.permission.ACCESS_FINE_LOCATION"));
159
160 // do we have required permission already, if so nothing to do
161 if (QtAndroidPrivate::checkPermission(coarsePermission) == QtAndroidPrivate::PermissionsResult::Denied
162 && QtAndroidPrivate::checkPermission(finePermission) == QtAndroidPrivate::PermissionsResult::Denied) {
163 qCWarning(QT_BT_ANDROID) << "Requesting ACCESS_*_LOCATION permission";
164
165 QAndroidJniEnvironment env;
166 const QHash<QString, QtAndroidPrivate::PermissionsResult> results =
167 QtAndroidPrivate::requestPermissionsSync(env, QStringList() << coarsePermission << finePermission);
168
169 bool permissionReceived = false;
170 for (const QString &permission: results.keys()) {
171 qCDebug(QT_BT_ANDROID) << permission << (results[permission] == QtAndroidPrivate::PermissionsResult::Denied);
172 if ((permission == coarsePermission || permission == finePermission)
173 && results[permission] == QtAndroidPrivate::PermissionsResult::Granted) {
174 permissionReceived = true;
175 break;
176 }
177 }
178 if (!permissionReceived) {
179 qCWarning(QT_BT_ANDROID) << "Search not possible due to missing permission (ACCESS_COARSE|FINE_LOCATION)";
180 lastError = QBluetoothDeviceDiscoveryAgent::UnknownError;
181 errorString = QBluetoothDeviceDiscoveryAgent::tr("Missing Location permission. Search is not possible.");
182 emit q->error(lastError);
183 return;
184 }
185 }
186
187 qCWarning(QT_BT_ANDROID) << "ACCESS_COARSE|FINE_LOCATION permission available";
188 }
189
190 // install Java BroadcastReceiver
191 if (!receiver) {
192 // SDP based device discovery
193 receiver = new DeviceDiscoveryBroadcastReceiver();
194 qRegisterMetaType<QBluetoothDeviceInfo>();
195 QObject::connect(receiver, SIGNAL(deviceDiscovered(QBluetoothDeviceInfo,bool)),
196 this, SLOT(processDiscoveredDevices(QBluetoothDeviceInfo,bool)));
197 QObject::connect(receiver, SIGNAL(finished()), this, SLOT(processSdpDiscoveryFinished()));
198 }
199
200 discoveredDevices.clear();
201
202 // by arbitrary definition we run classic search first
203 if (requestedMethods & QBluetoothDeviceDiscoveryAgent::ClassicMethod) {
204 const bool success = adapter.callMethod<jboolean>("startDiscovery");
205 if (!success) {
206 lastError = QBluetoothDeviceDiscoveryAgent::InputOutputError;
207 errorString = QBluetoothDeviceDiscoveryAgent::tr("Classic Discovery cannot be started");
208 emit q->error(lastError);
209 return;
210 }
211
212 m_active = SDPScanActive;
213 qCDebug(QT_BT_ANDROID)
214 << "QBluetoothDeviceDiscoveryAgentPrivate::start() - Classic search successfully started.";
215 } else {
216 // LE search only requested
217 Q_ASSERT(requestedMethods & QBluetoothDeviceDiscoveryAgent::LowEnergyMethod);
218
219 if (QtAndroidPrivate::androidSdkVersion() < 18) {
220 qCDebug(QT_BT_ANDROID) << "Skipping Bluetooth Low Energy device scan due to"
221 "insufficient Android version.";
222 m_active = NoScanActive;
223 lastError = QBluetoothDeviceDiscoveryAgent::UnsupportedDiscoveryMethod;
224 errorString = QBluetoothDeviceDiscoveryAgent::tr("Low Energy Discovery not supported");
225 emit q->error(lastError);
226 return;
227 }
228
229 startLowEnergyScan();
230 }
231}
232
233void QBluetoothDeviceDiscoveryAgentPrivate::stop()
234{
235 Q_Q(QBluetoothDeviceDiscoveryAgent);
236
237 if (m_active == NoScanActive)
238 return;
239
240 if (m_active == SDPScanActive) {
241 if (pendingCancel)
242 return;
243
244 pendingCancel = true;
245 pendingStart = false;
246 bool success = adapter.callMethod<jboolean>("cancelDiscovery");
247 if (!success) {
248 lastError = QBluetoothDeviceDiscoveryAgent::InputOutputError;
249 errorString = QBluetoothDeviceDiscoveryAgent::tr("Discovery cannot be stopped");
250 emit q->error(lastError);
251 return;
252 }
253 } else if (m_active == BtleScanActive) {
254 stopLowEnergyScan();
255 }
256}
257
258void QBluetoothDeviceDiscoveryAgentPrivate::processSdpDiscoveryFinished()
259{
260 // We need to guard because Android sends two DISCOVERY_FINISHED when cancelling
261 // Also if we have two active agents both receive the same signal.
262 // If this one is not active ignore the device information
263 if (m_active != SDPScanActive)
264 return;
265
266 Q_Q(QBluetoothDeviceDiscoveryAgent);
267
268 if (pendingCancel && !pendingStart) {
269 m_active = NoScanActive;
270 pendingCancel = false;
271 emit q->canceled();
272 } else if (pendingStart) {
273 pendingStart = pendingCancel = false;
274 start(requestedMethods);
275 } else {
276 // check that it didn't finish due to turned off Bluetooth Device
277 const int state = adapter.callMethod<jint>("getState");
278 if (state != 12) { // BluetoothAdapter.STATE_ON
279 m_active = NoScanActive;
280 lastError = QBluetoothDeviceDiscoveryAgent::PoweredOffError;
281 errorString = QBluetoothDeviceDiscoveryAgent::tr("Device is powered off");
282 emit q->error(lastError);
283 return;
284 }
285
286 // no BTLE scan requested
287 if (!(requestedMethods & QBluetoothDeviceDiscoveryAgent::LowEnergyMethod)) {
288 m_active = NoScanActive;
289 emit q->finished();
290 return;
291 }
292
293 // start LE scan if supported
294 if (QtAndroidPrivate::androidSdkVersion() < 18) {
295 qCDebug(QT_BT_ANDROID) << "Skipping Bluetooth Low Energy device scan";
296 m_active = NoScanActive;
297 emit q->finished();
298 } else {
299 startLowEnergyScan();
300 }
301 }
302}
303
304void QBluetoothDeviceDiscoveryAgentPrivate::processDiscoveredDevices(
305 const QBluetoothDeviceInfo &info, bool isLeResult)
306{
307 // If we have two active agents both receive the same signal.
308 // If this one is not active ignore the device information
309 if (m_active != SDPScanActive && !isLeResult)
310 return;
311 if (m_active != BtleScanActive && isLeResult)
312 return;
313
314 Q_Q(QBluetoothDeviceDiscoveryAgent);
315
316 // Android Classic scan and LE scan can find the same device under different names
317 // The classic name finds the SDP based device name, the LE scan finds the name in
318 // the advertisement package.
319 // If address is same but name different then we keep both entries.
320
321 for (int i = 0; i < discoveredDevices.size(); i++) {
322 if (discoveredDevices[i].address() == info.address()) {
323 QBluetoothDeviceInfo::Fields updatedFields = QBluetoothDeviceInfo::Field::None;
324 if (discoveredDevices[i].rssi() != info.rssi()) {
325 qCDebug(QT_BT_ANDROID) << "Updating RSSI for" << info.address()
326 << info.rssi();
327 discoveredDevices[i].setRssi(info.rssi());
328 updatedFields.setFlag(QBluetoothDeviceInfo::Field::RSSI);
329 }
330 if (discoveredDevices[i].manufacturerData() != info.manufacturerData()) {
331 qCDebug(QT_BT_ANDROID) << "Updating manufacturer data for" << info.address();
332 const QVector<quint16> keys = info.manufacturerIds();
333 for (auto key: keys)
334 discoveredDevices[i].setManufacturerData(key, info.manufacturerData(key));
335 updatedFields.setFlag(QBluetoothDeviceInfo::Field::ManufacturerData);
336 }
337
338 if (lowEnergySearchTimeout > 0) {
339 if (discoveredDevices[i] != info) {
340 if (discoveredDevices.at(i).name() == info.name()) {
341 qCDebug(QT_BT_ANDROID) << "Almost Duplicate " << info.address()
342 << info.name() << "- replacing in place";
343 discoveredDevices.replace(i, info);
344 emit q->deviceDiscovered(info);
345 }
346 } else {
347 if (!updatedFields.testFlag(QBluetoothDeviceInfo::Field::None))
348 emit q->deviceUpdated(discoveredDevices[i], updatedFields);
349 }
350
351 return;
352 }
353
354 discoveredDevices.replace(i, info);
355 emit q->deviceDiscovered(info);
356
357 if (!updatedFields.testFlag(QBluetoothDeviceInfo::Field::None))
358 emit q->deviceUpdated(discoveredDevices[i], updatedFields);
359
360 return;
361 }
362 }
363
364 discoveredDevices.append(info);
365 qCDebug(QT_BT_ANDROID) << "Device found: " << info.name() << info.address().toString()
366 << "isLeScanResult:" << isLeResult
367 << "Manufacturer data size:" << info.manufacturerData().size();
368 emit q->deviceDiscovered(info);
369}
370
371void QBluetoothDeviceDiscoveryAgentPrivate::startLowEnergyScan()
372{
373 Q_Q(QBluetoothDeviceDiscoveryAgent);
374
375 m_active = BtleScanActive;
376
377 QAndroidJniEnvironment env;
378 if (!leScanner.isValid()) {
379 leScanner = QAndroidJniObject("org/qtproject/qt5/android/bluetooth/QtBluetoothLE");
380 if (env->ExceptionCheck() || !leScanner.isValid()) {
381 qCWarning(QT_BT_ANDROID) << "Cannot load BTLE device scan class";
382 env->ExceptionDescribe();
383 env->ExceptionClear();
384 m_active = NoScanActive;
385 emit q->finished();
386 return;
387 }
388
389 leScanner.setField<jlong>("qtObject", reinterpret_cast<long>(receiver));
390 }
391
392 jboolean result = leScanner.callMethod<jboolean>("scanForLeDevice", "(Z)Z", true);
393 if (!result) {
394 qCWarning(QT_BT_ANDROID) << "Cannot start BTLE device scanner";
395 m_active = NoScanActive;
396 emit q->finished();
397 return;
398 }
399
400 // wait interval and sum up what was found
401 if (!leScanTimeout) {
402 leScanTimeout = new QTimer(this);
403 leScanTimeout->setSingleShot(true);
404 connect(leScanTimeout, &QTimer::timeout,
405 this, &QBluetoothDeviceDiscoveryAgentPrivate::stopLowEnergyScan);
406 }
407
408 if (lowEnergySearchTimeout > 0) { // otherwise no timeout and stop() required
409 leScanTimeout->setInterval(lowEnergySearchTimeout);
410 leScanTimeout->start();
411 }
412
413 qCDebug(QT_BT_ANDROID)
414 << "QBluetoothDeviceDiscoveryAgentPrivate::start() - Low Energy search successfully started.";
415}
416
417void QBluetoothDeviceDiscoveryAgentPrivate::stopLowEnergyScan()
418{
419 jboolean result = leScanner.callMethod<jboolean>("scanForLeDevice", "(Z)Z", false);
420 if (!result)
421 qCWarning(QT_BT_ANDROID) << "Cannot stop BTLE device scanner";
422
423 m_active = NoScanActive;
424
425 Q_Q(QBluetoothDeviceDiscoveryAgent);
426 if (leScanTimeout->isActive()) {
427 // still active if this function was called from stop()
428 leScanTimeout->stop();
429 emit q->canceled();
430 } else {
431 // timeout -> regular stop
432 emit q->finished();
433 }
434}
435QT_END_NAMESPACE
436

Warning: That file was not part of the compilation database. It may have many parsing errors.