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(ui->quitButton, &QPushButton::clicked, this, &Chat::accept);
78 connect(ui->connectButton, &QPushButton::clicked, this, &Chat::connectClicked);
79 connect(ui->sendButton, &QPushButton::clicked, this, &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("Default (%1)", "%1 = Bluetooth address").
89 arg(localAdapters.at(0).address().toString()));
90 ui->secondAdapter->setText(localAdapters.at(1).address().toString());
91 ui->firstAdapter->setChecked(true);
92 connect(ui->firstAdapter, &QRadioButton::clicked, this, &Chat::newAdapterSelected);
93 connect(ui->secondAdapter, &QRadioButton::clicked, this, &Chat::newAdapterSelected);
94 QBluetoothLocalDevice adapter(localAdapters.at(0).address());
95 adapter.setHostMode(QBluetoothLocalDevice::HostDiscoverable);
96 }
97
98 //! [Create Chat Server]
99 server = new ChatServer(this);
100 connect(server, QOverload<const QString &>::of(&ChatServer::clientConnected),
101 this, &Chat::clientConnected);
102 connect(server, QOverload<const QString &>::of(&ChatServer::clientDisconnected),
103 this, QOverload<const QString &>::of(&Chat::clientDisconnected));
104 connect(server, &ChatServer::messageReceived,
105 this, &Chat::showMessage);
106 connect(this, &Chat::sendMessage, server, &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(clients);
118 delete server;
119}
120
121//! [clientConnected clientDisconnected]
122void Chat::clientConnected(const QString &name)
123{
124 ui->chat->insertPlainText(QString::fromLatin1("%1 has joined chat.\n").arg(name));
125}
126
127void Chat::clientDisconnected(const QString &name)
128{
129 ui->chat->insertPlainText(QString::fromLatin1("%1 has left.\n").arg(name));
130}
131//! [clientConnected clientDisconnected]
132
133//! [connected]
134void Chat::connected(const QString &name)
135{
136 ui->chat->insertPlainText(QString::fromLatin1("Joined chat with %1.\n").arg(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(currentAdapterIndex);
147 QBluetoothLocalDevice adapter(info.address());
148 adapter.setHostMode(QBluetoothLocalDevice::HostDiscoverable);
149 server->startServer(info.address());
150 localName = info.name();
151 }
152}
153
154int Chat::adapterFromUserSelection() const
155{
156 int result = 0;
157 QBluetoothAddress newAdapter = localAdapters.at(0).address();
158
159 if (ui->secondAdapter->isChecked()) {
160 newAdapter = localAdapters.at(1).address();
161 result = 1;
162 }
163 return result;
164}
165
166void Chat::reactOnSocketError(const QString &error)
167{
168 ui->chat->insertPlainText(error);
169}
170
171//! [clientDisconnected]
172void Chat::clientDisconnected()
173{
174 ChatClient *client = qobject_cast<ChatClient *>(sender());
175 if (client) {
176 clients.removeOne(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(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(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(client, &ChatClient::messageReceived,
213 this, &Chat::showMessage);
214 connect(client, &ChatClient::disconnected,
215 this, QOverload<>::of(&Chat::clientDisconnected));
216 connect(client, QOverload<const QString &>::of(&ChatClient::connected),
217 this, &Chat::connected);
218 connect(client, &ChatClient::socketErrorOccurred,
219 this, &Chat::reactOnSocketError);
220 connect(this, &Chat::sendMessage, client, &ChatClient::sendMessage);
221qDebug() << "Start client";
222 client->startClient(service);
223
224 clients.append(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(localName, ui->sendText->text());
238 emit sendMessage(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(QString::fromLatin1("%1: %2\n").arg(sender, message));
251 ui->chat->ensureCursorVisible();
252}
253//! [showMessage]
254

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