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 QtBluetooth module 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 "chat.h"
52#include "remoteselector.h"
53#include "chatserver.h"
54#include "chatclient.h"
55
56#include <QtCore/qdebug.h>
57
58#include <QtBluetooth/qbluetoothdeviceinfo.h>
59#include <QtBluetooth/qbluetoothlocaldevice.h>
60#include <QtBluetooth/qbluetoothuuid.h>
61
62#ifdef Q_OS_ANDROID
63#include <QtAndroidExtras/QtAndroid>
64#endif
65
66static const QLatin1String serviceUuid("e8e10f95-1a70-4b27-9ccf-02010264e9c8");
67#ifdef Q_OS_ANDROID
68static const QLatin1String reverseUuid("c8e96402-0102-cf9c-274b-701a950fe1e8");
69#endif
70
71Chat::Chat(QWidget *parent)
72 : QDialog(parent), ui(new Ui_Chat)
73{
74 //! [Construct UI]
75 ui->setupUi(this);
76
77 connect(sender: ui->quitButton, signal: &QPushButton::clicked, receiver: this, slot: &Chat::accept);
78 connect(sender: ui->connectButton, signal: &QPushButton::clicked, receiver: this, slot: &Chat::connectClicked);
79 connect(sender: ui->sendButton, signal: &QPushButton::clicked, receiver: this, slot: &Chat::sendClicked);
80 //! [Construct UI]
81
82 localAdapters = QBluetoothLocalDevice::allDevices();
83 if (localAdapters.count() < 2) {
84 ui->localAdapterBox->setVisible(false);
85 } else {
86 //we ignore more than two adapters
87 ui->localAdapterBox->setVisible(true);
88 ui->firstAdapter->setText(tr(s: "Default (%1)", c: "%1 = Bluetooth address").
89 arg(a: localAdapters.at(i: 0).address().toString()));
90 ui->secondAdapter->setText(localAdapters.at(i: 1).address().toString());
91 ui->firstAdapter->setChecked(true);
92 connect(sender: ui->firstAdapter, signal: &QRadioButton::clicked, receiver: this, slot: &Chat::newAdapterSelected);
93 connect(sender: ui->secondAdapter, signal: &QRadioButton::clicked, receiver: this, slot: &Chat::newAdapterSelected);
94 QBluetoothLocalDevice adapter(localAdapters.at(i: 0).address());
95 adapter.setHostMode(QBluetoothLocalDevice::HostDiscoverable);
96 }
97
98 //! [Create Chat Server]
99 server = new ChatServer(this);
100 connect(sender: server, signal: QOverload<const QString &>::of(ptr: &ChatServer::clientConnected),
101 receiver: this, slot: &Chat::clientConnected);
102 connect(sender: server, signal: QOverload<const QString &>::of(ptr: &ChatServer::clientDisconnected),
103 receiver: this, slot: QOverload<const QString &>::of(ptr: &Chat::clientDisconnected));
104 connect(sender: server, signal: &ChatServer::messageReceived,
105 receiver: this, slot: &Chat::showMessage);
106 connect(sender: this, signal: &Chat::sendMessage, receiver: server, slot: &ChatServer::sendMessage);
107 server->startServer();
108 //! [Create Chat Server]
109
110 //! [Get local device name]
111 localName = QBluetoothLocalDevice().name();
112 //! [Get local device name]
113}
114
115Chat::~Chat()
116{
117 qDeleteAll(c: clients);
118 delete server;
119}
120
121//! [clientConnected clientDisconnected]
122void Chat::clientConnected(const QString &name)
123{
124 ui->chat->insertPlainText(text: QString::fromLatin1(str: "%1 has joined chat.\n").arg(a: name));
125}
126
127void Chat::clientDisconnected(const QString &name)
128{
129 ui->chat->insertPlainText(text: QString::fromLatin1(str: "%1 has left.\n").arg(a: name));
130}
131//! [clientConnected clientDisconnected]
132
133//! [connected]
134void Chat::connected(const QString &name)
135{
136 ui->chat->insertPlainText(text: QString::fromLatin1(str: "Joined chat with %1.\n").arg(a: name));
137}
138//! [connected]
139
140void Chat::newAdapterSelected()
141{
142 const int newAdapterIndex = adapterFromUserSelection();
143 if (currentAdapterIndex != newAdapterIndex) {
144 server->stopServer();
145 currentAdapterIndex = newAdapterIndex;
146 const QBluetoothHostInfo info = localAdapters.at(i: currentAdapterIndex);
147 QBluetoothLocalDevice adapter(info.address());
148 adapter.setHostMode(QBluetoothLocalDevice::HostDiscoverable);
149 server->startServer(localAdapter: info.address());
150 localName = info.name();
151 }
152}
153
154int Chat::adapterFromUserSelection() const
155{
156 int result = 0;
157 QBluetoothAddress newAdapter = localAdapters.at(i: 0).address();
158
159 if (ui->secondAdapter->isChecked()) {
160 newAdapter = localAdapters.at(i: 1).address();
161 result = 1;
162 }
163 return result;
164}
165
166void Chat::reactOnSocketError(const QString &error)
167{
168 ui->chat->insertPlainText(text: error);
169}
170
171//! [clientDisconnected]
172void Chat::clientDisconnected()
173{
174 ChatClient *client = qobject_cast<ChatClient *>(object: sender());
175 if (client) {
176 clients.removeOne(t: client);
177 client->deleteLater();
178 }
179}
180//! [clientDisconnected]
181
182//! [Connect to remote service]
183void Chat::connectClicked()
184{
185 ui->connectButton->setEnabled(false);
186
187 // scan for services
188 const QBluetoothAddress adapter = localAdapters.isEmpty() ?
189 QBluetoothAddress() :
190 localAdapters.at(i: currentAdapterIndex).address();
191
192 RemoteSelector remoteSelector(adapter);
193#ifdef Q_OS_ANDROID
194 if (QtAndroid::androidSdkVersion() >= 23)
195 remoteSelector.startDiscovery(QBluetoothUuid(reverseUuid));
196 else
197 remoteSelector.startDiscovery(QBluetoothUuid(serviceUuid));
198#else
199 remoteSelector.startDiscovery(uuid: QBluetoothUuid(serviceUuid));
200#endif
201 if (remoteSelector.exec() == QDialog::Accepted) {
202 QBluetoothServiceInfo service = remoteSelector.service();
203
204 qDebug() << "Connecting to service 2" << service.serviceName()
205 << "on" << service.device().name();
206
207 // Create client
208 qDebug() << "Going to create client";
209 ChatClient *client = new ChatClient(this);
210qDebug() << "Connecting...";
211
212 connect(sender: client, signal: &ChatClient::messageReceived,
213 receiver: this, slot: &Chat::showMessage);
214 connect(sender: client, signal: &ChatClient::disconnected,
215 receiver: this, slot: QOverload<>::of(ptr: &Chat::clientDisconnected));
216 connect(sender: client, signal: QOverload<const QString &>::of(ptr: &ChatClient::connected),
217 receiver: this, slot: &Chat::connected);
218 connect(sender: client, signal: &ChatClient::socketErrorOccurred,
219 receiver: this, slot: &Chat::reactOnSocketError);
220 connect(sender: this, signal: &Chat::sendMessage, receiver: client, slot: &ChatClient::sendMessage);
221qDebug() << "Start client";
222 client->startClient(remoteService: service);
223
224 clients.append(t: client);
225 }
226
227 ui->connectButton->setEnabled(true);
228}
229//! [Connect to remote service]
230
231//! [sendClicked]
232void Chat::sendClicked()
233{
234 ui->sendButton->setEnabled(false);
235 ui->sendText->setEnabled(false);
236
237 showMessage(sender: localName, message: ui->sendText->text());
238 emit sendMessage(message: ui->sendText->text());
239
240 ui->sendText->clear();
241
242 ui->sendText->setEnabled(true);
243 ui->sendButton->setEnabled(true);
244}
245//! [sendClicked]
246
247//! [showMessage]
248void Chat::showMessage(const QString &sender, const QString &message)
249{
250 ui->chat->insertPlainText(text: QString::fromLatin1(str: "%1: %2\n").arg(a1: sender, a2: message));
251 ui->chat->ensureCursorVisible();
252}
253//! [showMessage]
254

source code of qtconnectivity/examples/bluetooth/btchat/chat.cpp