1/****************************************************************************
2**
3** Copyright (C) 2017 The Qt Company Ltd.
4** Contact: https://www.qt.io/licensing/
5**
6** This file is part of the documentation of the Qt Toolkit.
7**
8** $QT_BEGIN_LICENSE:BSD$
9** Commercial License Usage
10** Licensees holding valid commercial Qt licenses may use this file in
11** accordance with the commercial license agreement provided with the
12** Software or, alternatively, in accordance with the terms contained in
13** a written agreement between you and The Qt Company. For licensing terms
14** and conditions see https://www.qt.io/terms-conditions. For further
15** information use the contact form at https://www.qt.io/contact-us.
16**
17** BSD License Usage
18** Alternatively, you may use this file under the terms of the BSD license
19** as follows:
20**
21** "Redistribution and use in source and binary forms, with or without
22** modification, are permitted provided that the following conditions are
23** met:
24** * Redistributions of source code must retain the above copyright
25** notice, this list of conditions and the following disclaimer.
26** * Redistributions in binary form must reproduce the above copyright
27** notice, this list of conditions and the following disclaimer in
28** the documentation and/or other materials provided with the
29** distribution.
30** * Neither the name of The Qt Company Ltd nor the names of its
31** contributors may be used to endorse or promote products derived
32** from this software without specific prior written permission.
33**
34**
35** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
36** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
37** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
38** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
39** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
40** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
41** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
42** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
43** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
44** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
45** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
46**
47** $QT_END_LICENSE$
48**
49****************************************************************************/
50
51//! [include]
52#include <QtBluetooth/QBluetoothLocalDevice>
53//! [include]
54#include <QtCore/QCoreApplication>
55#include <QtCore/QDebug>
56#include <QtCore/QFile>
57#include <QtCore/QObject>
58#include <QtBluetooth/QBluetoothDeviceDiscoveryAgent>
59#include <QtBluetooth/QBluetoothServiceDiscoveryAgent>
60#include <QtBluetooth/QBluetoothTransferManager>
61#include <QtBluetooth/QBluetoothTransferRequest>
62#include <QtBluetooth/QBluetoothTransferReply>
63
64#include <QtBluetooth/QLowEnergyController>
65#include <QtBluetooth/QLowEnergyService>
66#include <QtBluetooth/QLowEnergyCharacteristic>
67
68//! [namespace]
69QT_USE_NAMESPACE
70//! [namespace]
71
72class MyClass : public QObject
73{
74 Q_OBJECT
75public:
76 MyClass() : QObject() {}
77 void localDevice();
78 void startDeviceDiscovery();
79 void startServiceDiscovery();
80 void objectPush();
81 void btleSharedData();
82 void enableCharNotifications();
83
84public slots:
85 void deviceDiscovered(const QBluetoothDeviceInfo &device);
86 void serviceDiscovered(const QBluetoothServiceInfo &service);
87 void transferFinished(QBluetoothTransferReply* reply);
88 void error(QBluetoothTransferReply::TransferError errorType);
89 void characteristicChanged(const QLowEnergyCharacteristic& ,const QByteArray&);
90};
91
92void MyClass::localDevice() {
93//! [turningon]
94QBluetoothLocalDevice localDevice;
95QString localDeviceName;
96
97// Check if Bluetooth is available on this device
98if (localDevice.isValid()) {
99
100 // Turn Bluetooth on
101 localDevice.powerOn();
102
103 // Read local device name
104 localDeviceName = localDevice.name();
105
106 // Make it visible to others
107 localDevice.setHostMode(QBluetoothLocalDevice::HostDiscoverable);
108
109 // Get connected devices
110 QList<QBluetoothAddress> remotes;
111 remotes = localDevice.connectedDevices();
112}
113//! [turningon]
114
115
116}
117
118//! [device_discovery]
119void MyClass::startDeviceDiscovery()
120{
121
122 // Create a discovery agent and connect to its signals
123 QBluetoothDeviceDiscoveryAgent *discoveryAgent = new QBluetoothDeviceDiscoveryAgent(this);
124 connect(sender: discoveryAgent, SIGNAL(deviceDiscovered(QBluetoothDeviceInfo)),
125 receiver: this, SLOT(deviceDiscovered(QBluetoothDeviceInfo)));
126
127 // Start a discovery
128 discoveryAgent->start();
129
130 //...
131}
132
133// In your local slot, read information about the found devices
134void MyClass::deviceDiscovered(const QBluetoothDeviceInfo &device)
135{
136 qDebug() << "Found new device:" << device.name() << '(' << device.address().toString() << ')';
137}
138//! [device_discovery]
139
140//! [service_discovery]
141void MyClass::startServiceDiscovery()
142{
143
144 // Create a discovery agent and connect to its signals
145 QBluetoothServiceDiscoveryAgent *discoveryAgent = new QBluetoothServiceDiscoveryAgent(this);
146 connect(sender: discoveryAgent, SIGNAL(serviceDiscovered(QBluetoothServiceInfo)),
147 receiver: this, SLOT(serviceDiscovered(QBluetoothServiceInfo)));
148
149 // Start a discovery
150 discoveryAgent->start();
151
152 //...
153}
154
155// In your local slot, read information about the found devices
156void MyClass::serviceDiscovered(const QBluetoothServiceInfo &service)
157{
158 qDebug() << "Found new service:" << service.serviceName()
159 << '(' << service.device().address().toString() << ')';
160}
161//! [service_discovery]
162
163void MyClass::objectPush()
164{
165//! [sendfile]
166// Create a transfer manager
167QBluetoothTransferManager *transferManager = new QBluetoothTransferManager(this);
168
169// Create the transfer request and file to be sent
170QBluetoothAddress remoteAddress("00:11:22:33:44:55:66");
171QBluetoothTransferRequest request(remoteAddress);
172QFile *file = new QFile("testfile.txt");
173
174// Ask the transfer manager to send it
175QBluetoothTransferReply *reply = transferManager->put(request, data: file);
176if (reply->error() == QBluetoothTransferReply::NoError) {
177
178 // Connect to the reply's signals to be informed about the status and do cleanups when done
179 QObject::connect(sender: reply, SIGNAL(finished(QBluetoothTransferReply*)),
180 receiver: this, SLOT(transferFinished(QBluetoothTransferReply*)));
181 QObject::connect(sender: reply, SIGNAL(error(QBluetoothTransferReply::TransferError)),
182 receiver: this, SLOT(error(QBluetoothTransferReply::TransferError)));
183} else {
184 qWarning() << "Cannot push testfile.txt:" << reply->errorString();
185}
186//! [sendfile]
187}
188
189void MyClass::transferFinished(QBluetoothTransferReply* /*reply*/)
190{
191}
192
193void MyClass::error(QBluetoothTransferReply::TransferError /*errorType*/)
194{
195}
196
197void MyClass::characteristicChanged(const QLowEnergyCharacteristic &, const QByteArray &)
198{
199}
200
201void MyClass::btleSharedData()
202{
203 QBluetoothDeviceInfo remoteDevice;
204
205//! [data_share_qlowenergyservice]
206 QLowEnergyService *first, *second;
207 QLowEnergyController control(remoteDevice);
208 control.connectToDevice();
209
210 // waiting for connection
211
212 first = control.createServiceObject(service: QBluetoothUuid::BatteryService);
213 second = control.createServiceObject(service: QBluetoothUuid::BatteryService);
214 Q_ASSERT(first->state() == QLowEnergyService::DiscoveryRequired);
215 Q_ASSERT(first->state() == second->state());
216
217 first->discoverDetails();
218
219 Q_ASSERT(first->state() == QLowEnergyService::DiscoveringServices);
220 Q_ASSERT(first->state() == second->state());
221//! [data_share_qlowenergyservice]
222}
223
224void MyClass::enableCharNotifications()
225{
226 QBluetoothDeviceInfo remoteDevice;
227 QLowEnergyService *service;
228 QLowEnergyController *control = QLowEnergyController::createCentral(remoteDevice, parent: this);
229 control->connectToDevice();
230
231
232 service = control->createServiceObject(service: QBluetoothUuid::BatteryService, parent: this);
233 if (!service)
234 return;
235
236 service->discoverDetails();
237
238 //... wait until discovered
239
240//! [enable_btle_notifications]
241 //PreCondition: service details already discovered
242 QLowEnergyCharacteristic batteryLevel = service->characteristic(
243 uuid: QBluetoothUuid::BatteryLevel);
244 if (!batteryLevel.isValid())
245 return;
246
247 QLowEnergyDescriptor notification = batteryLevel.descriptor(
248 uuid: QBluetoothUuid::ClientCharacteristicConfiguration);
249 if (!notification.isValid())
250 return;
251
252 // establish hook into notifications
253 connect(sender: service, SIGNAL(characteristicChanged(QLowEnergyCharacteristic,QByteArray)),
254 receiver: this, SLOT(characteristicChanged(QLowEnergyCharacteristic,QByteArray)));
255
256 // enable notification
257 service->writeDescriptor(descriptor: notification, newValue: QByteArray::fromHex(hexEncoded: "0100"));
258
259 // disable notification
260 //service->writeDescriptor(notification, QByteArray::fromHex("0000"));
261
262 // wait until descriptorWritten() signal is emitted
263 // to confirm successful write
264//! [enable_btle_notifications]
265}
266
267
268
269int main(int argc, char** argv)
270{
271 QCoreApplication app(argc, argv);
272 MyClass cl;
273
274 return app.exec();
275}
276
277#include "doc_src_qtbluetooth.moc"
278

source code of qtconnectivity/src/bluetooth/doc/snippets/doc_src_qtbluetooth.cpp