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
|
#include <QShortcut>
#include <QDebug>
#include <QMessageBox>
#include <QMenu>
#include "ui_btdeviceselectiondialog.h"
#include "btdeviceselectiondialog.h"
BtDeviceSelectionDialog::BtDeviceSelectionDialog(QWidget *parent) :
QDialog(parent),
localDevice(new QBluetoothLocalDevice),
ui(new Ui::BtDeviceSelectionDialog)
{
ui->setupUi(this);
// Quit button callbacks
QShortcut *quit = new QShortcut(QKeySequence(Qt::CTRL + Qt::Key_Q), this);
connect(quit, SIGNAL(activated()), this, SLOT(reject()));
connect(ui->quit, SIGNAL(clicked()), this, SLOT(reject()));
// Disable the save button because there is no device selected
ui->save->setEnabled(false);
connect(ui->discoveredDevicesList, SIGNAL(itemClicked(QListWidgetItem*)),
this, SLOT(itemClicked(QListWidgetItem*)));
// Populate the list with local bluetooth devices
QList<QBluetoothHostInfo> localAvailableDevices = localDevice->allDevices();
int availableDevicesSize = localAvailableDevices.size();
if (availableDevicesSize > 1) {
int defaultDeviceIndex = -1;
for (int it = 0; it < availableDevicesSize; it++) {
QBluetoothHostInfo localAvailableDevice = localAvailableDevices.at(it);
ui->localSelectedDevice->addItem(localAvailableDevice.name(),
QVariant::fromValue(localAvailableDevice.address()));
if (localDevice->address() == localAvailableDevice.address())
defaultDeviceIndex = it;
}
// Positionate the current index to the default device and register to index changes events
ui->localSelectedDevice->setCurrentIndex(defaultDeviceIndex);
connect(ui->localSelectedDevice, SIGNAL(currentIndexChanged(int)),
this, SLOT(localDeviceChanged(int)));
} else {
// If there is only one local Bluetooth adapter hide the combobox and the label
ui->selectDeviceLable->hide();
ui->localSelectedDevice->hide();
}
// Update the UI information about the local device
updateLocalDeviceInformation();
// Initialize the device discovery agent
if (localDevice->isValid())
initializeDeviceDiscoveryAgent();
}
BtDeviceSelectionDialog::~BtDeviceSelectionDialog()
{
delete ui;
}
void BtDeviceSelectionDialog::on_changeDeviceState_clicked()
{
if (localDevice->hostMode() == QBluetoothLocalDevice::HostPoweredOff) {
ui->dialogStatus->setText("Trying to turn on the local Bluetooth device...");
localDevice->powerOn();
} else {
ui->dialogStatus->setText("Trying to turn off the local Bluetooth device...");
localDevice->setHostMode(QBluetoothLocalDevice::HostPoweredOff);
}
}
void BtDeviceSelectionDialog::on_save_clicked()
{
// Get the selected device. There will be always a selected device if the save button is enabled.
QListWidgetItem *currentItem = ui->discoveredDevicesList->currentItem();
QBluetoothDeviceInfo remoteDeviceInfo = currentItem->data(Qt::UserRole).value<QBluetoothDeviceInfo>();
// Save the selected device
selectedRemoteDeviceInfo = QSharedPointer<QBluetoothDeviceInfo>(new QBluetoothDeviceInfo(remoteDeviceInfo));
if (remoteDeviceDiscoveryAgent->isActive()) {
// Stop the SDP agent if the clear button is pressed and enable the Scan button
remoteDeviceDiscoveryAgent->stop();
ui->scan->setEnabled(true);
}
// Close the device selection dialog and set the result code to Accepted
accept();
}
void BtDeviceSelectionDialog::on_clear_clicked()
{
ui->dialogStatus->setText("Remote devices list was cleaned.");
ui->discoveredDevicesList->clear();
ui->save->setEnabled(false);
if (remoteDeviceDiscoveryAgent->isActive()) {
// Stop the SDP agent if the clear button is pressed and enable the Scan button
remoteDeviceDiscoveryAgent->stop();
ui->scan->setEnabled(true);
}
}
void BtDeviceSelectionDialog::on_scan_clicked()
{
ui->dialogStatus->setText("Scanning for remote devices...");
remoteDeviceDiscoveryAgent->start();
ui->scan->setEnabled(false);
}
void BtDeviceSelectionDialog::remoteDeviceScanFinished()
{
ui->dialogStatus->setText("Scanning finished.");
ui->scan->setEnabled(true);
}
void BtDeviceSelectionDialog::hostModeStateChanged(QBluetoothLocalDevice::HostMode mode)
{
bool on = !(mode == QBluetoothLocalDevice::HostPoweredOff);
ui->dialogStatus->setText(QString("The local Bluetooth device was turned %1.")
.arg(on? "ON" : "OFF"));
ui->deviceState->setChecked(on);
ui->scan->setEnabled(on);
}
void BtDeviceSelectionDialog::addRemoteDevice(const QBluetoothDeviceInfo &remoteDeviceInfo)
{
QString deviceLable = QString("%1 (%2)").arg(remoteDeviceInfo.name()).arg(remoteDeviceInfo.address().toString());
QList<QListWidgetItem *> itemsWithSameSignature = ui->discoveredDevicesList->findItems(deviceLable, Qt::MatchStartsWith);
// Check if the remote device is already in the list
if (itemsWithSameSignature.empty()) {
QListWidgetItem *item = new QListWidgetItem(deviceLable);
QBluetoothLocalDevice::Pairing pairingStatus = localDevice->pairingStatus(remoteDeviceInfo.address());
item->setData(Qt::UserRole, QVariant::fromValue(remoteDeviceInfo));
if (pairingStatus == QBluetoothLocalDevice::Paired) {
item->setText(QString("%1 [State: PAIRED]").arg(item->text()));
item->setBackgroundColor(QColor(Qt::gray));
} else if (pairingStatus == QBluetoothLocalDevice::AuthorizedPaired) {
item->setText(QString("%1 [State: AUTHORIZED_PAIRED]").arg(item->text()));
item->setBackgroundColor(QColor(Qt::blue));
} else {
item->setText(QString("%1 [State: UNPAIRED]").arg(item->text()));
item->setTextColor(QColor(Qt::black));
}
ui->discoveredDevicesList->addItem(item);
}
}
void BtDeviceSelectionDialog::itemClicked(QListWidgetItem *item)
{
QBluetoothDeviceInfo remoteDeviceInfo = item->data(Qt::UserRole).value<QBluetoothDeviceInfo>();
QBluetoothLocalDevice::Pairing pairingStatus = localDevice->pairingStatus(remoteDeviceInfo.address());
if (pairingStatus == QBluetoothLocalDevice::Unpaired) {
ui->dialogStatus->setText(QString("The device %1 must be paired in order to be used. Please use the context menu for pairing options.")
.arg(remoteDeviceInfo.address().toString()));
ui->save->setEnabled(false);
} else {
ui->dialogStatus->setText(QString("The device %1 can be used for connection. You can press the Save button.")
.arg(remoteDeviceInfo.address().toString()));
ui->save->setEnabled(true);
}
}
void BtDeviceSelectionDialog::localDeviceChanged(int index)
{
QBluetoothAddress localDeviceSelectedAddress = ui->localSelectedDevice->itemData(index, Qt::UserRole).value<QBluetoothAddress>();
// Delete the old localDevice
if (localDevice)
delete localDevice;
// Create a new local device using the selected address
localDevice = new QBluetoothLocalDevice(localDeviceSelectedAddress);
ui->dialogStatus->setText(QString("The local device was changed."));
// Clear the discovered devices list
on_clear_clicked();
// Update the UI information about the local device
updateLocalDeviceInformation();
// Initialize the device discovery agent
if (localDevice->isValid())
initializeDeviceDiscoveryAgent();
}
void BtDeviceSelectionDialog::displayPairingMenu(const QPoint &pos)
{
QMenu menu(this);
QAction *pairAction = menu.addAction("Pair");
QAction *removePairAction = menu.addAction("Remove Pairing");
QAction *chosenAction = menu.exec(ui->discoveredDevicesList->viewport()->mapToGlobal(pos));
QListWidgetItem *currentItem = ui->discoveredDevicesList->currentItem();
QBluetoothDeviceInfo currentRemoteDeviceInfo = currentItem->data(Qt::UserRole).value<QBluetoothDeviceInfo>();
QBluetoothLocalDevice::Pairing pairingStatus = localDevice->pairingStatus(currentRemoteDeviceInfo.address());
//TODO: disable the actions
if (pairingStatus == QBluetoothLocalDevice::Unpaired) {
pairAction->setEnabled(true);
removePairAction->setEnabled(false);
} else {
pairAction->setEnabled(false);
removePairAction->setEnabled(true);
}
if (chosenAction == pairAction) {
ui->dialogStatus->setText(QString("Trying to pair device %1")
.arg(currentRemoteDeviceInfo.address().toString()));
localDevice->requestPairing(currentRemoteDeviceInfo.address(), QBluetoothLocalDevice::Paired);
} else if (chosenAction == removePairAction) {
ui->dialogStatus->setText(QString("Trying to unpair device %1")
.arg(currentRemoteDeviceInfo.address().toString()));
localDevice->requestPairing(currentRemoteDeviceInfo.address(), QBluetoothLocalDevice::Unpaired);
}
}
void BtDeviceSelectionDialog::pairingFinished(const QBluetoothAddress &address, QBluetoothLocalDevice::Pairing pairing)
{
QString remoteDeviceStringAddress = address.toString();
QList<QListWidgetItem *> items = ui->discoveredDevicesList->findItems(remoteDeviceStringAddress, Qt::MatchContains);
if (pairing == QBluetoothLocalDevice::Paired || pairing == QBluetoothLocalDevice::Paired ) {
ui->dialogStatus->setText(QString("Device %1 was paired.")
.arg(remoteDeviceStringAddress));
for (int i = 0; i < items.count(); ++i) {
QListWidgetItem *item = items.at(i);
item->setText(QString("%1 [State: PAIRED]").arg(remoteDeviceStringAddress));
item->setBackgroundColor(QColor(Qt::gray));
}
QListWidgetItem *currentItem = ui->discoveredDevicesList->currentItem();
if (currentItem != NULL && currentItem->text().contains(remoteDeviceStringAddress, Qt::CaseInsensitive)) {
ui->dialogStatus->setText(QString("The device %1 can now be used for connection. You can press the Save button.")
.arg(remoteDeviceStringAddress));
ui->save->setEnabled(true);
}
} else {
ui->dialogStatus->setText(QString("Device %1 was unpaired.")
.arg(remoteDeviceStringAddress));
for (int i = 0; i < items.count(); ++i) {
QListWidgetItem *item = items.at(i);
item->setText(QString("%1 [State: UNPAIRED]").arg(remoteDeviceStringAddress));
item->setBackgroundColor(QColor(Qt::white));
}
QListWidgetItem *currentItem = ui->discoveredDevicesList->currentItem();
if (currentItem != NULL && currentItem->text().contains(remoteDeviceStringAddress, Qt::CaseInsensitive)) {
ui->dialogStatus->setText(QString("The device %1 must be paired in order to be used. Please use the context menu for pairing options.")
.arg(remoteDeviceStringAddress));
ui->save->setEnabled(false);
}
}
}
void BtDeviceSelectionDialog::error(QBluetoothLocalDevice::Error error)
{
ui->dialogStatus->setText(QString("Local device error: %1.")
.arg((error == QBluetoothLocalDevice::PairingError)? "Pairing error" : "Unknown error"));
}
void BtDeviceSelectionDialog::deviceDiscoveryError(QBluetoothDeviceDiscoveryAgent::Error error)
{
QString errorDescription;
switch (error) {
case QBluetoothDeviceDiscoveryAgent::PoweredOffError:
errorDescription = QString("The Bluetooth adaptor is powered off, power it on before doing discovery.");
break;
case QBluetoothDeviceDiscoveryAgent::InputOutputError:
errorDescription = QString("Writing or reading from the device resulted in an error.");
break;
default:
errorDescription = QString("An unknown error has occurred.");
break;
}
ui->dialogStatus->setText(QString("Device discovery error: %1.").arg(errorDescription));
}
QString BtDeviceSelectionDialog::getSelectedDeviceAddress()
{
if (selectedRemoteDeviceInfo) {
return selectedRemoteDeviceInfo.data()->address().toString();
}
return QString();
}
QString BtDeviceSelectionDialog::getSelectedDeviceName()
{
if (selectedRemoteDeviceInfo) {
return selectedRemoteDeviceInfo.data()->name();
}
return QString();
}
void BtDeviceSelectionDialog::updateLocalDeviceInformation()
{
// Check if the selected Bluetooth device can be accessed
if (!localDevice->isValid()) {
QString na = QString("Not available");
// Update the UI information
ui->deviceAddress->setText(na);
ui->deviceName->setText(na);
// Announce the user that there is a problem with the selected local Bluetooth adapter
ui->dialogStatus->setText(QString("The local Bluetooth adapter cannot be accessed."));
// Disable the buttons
ui->save->setEnabled(false);
ui->scan->setEnabled(false);
ui->clear->setEnabled(false);
ui->changeDeviceState->setEnabled(false);
return;
}
// Set UI information about the local device
ui->deviceAddress->setText(localDevice->address().toString());
ui->deviceName->setText(localDevice->name());
connect(localDevice, SIGNAL(hostModeStateChanged(QBluetoothLocalDevice::HostMode)),
this, SLOT(hostModeStateChanged(QBluetoothLocalDevice::HostMode)));
// Initialize the state of the local device and activate/deactive the scan button
hostModeStateChanged(localDevice->hostMode());
// Add context menu for devices to be able to pair them
ui->discoveredDevicesList->setContextMenuPolicy(Qt::CustomContextMenu);
connect(ui->discoveredDevicesList, SIGNAL(customContextMenuRequested(QPoint)),
this, SLOT(displayPairingMenu(QPoint)));
connect(localDevice, SIGNAL(pairingFinished(QBluetoothAddress, QBluetoothLocalDevice::Pairing)),
this, SLOT(pairingFinished(QBluetoothAddress, QBluetoothLocalDevice::Pairing)));
connect(localDevice, SIGNAL(error(QBluetoothLocalDevice::Error)),
this, SLOT(error(QBluetoothLocalDevice::Error)));
}
void BtDeviceSelectionDialog::initializeDeviceDiscoveryAgent()
{
// Intialize the discovery agent
remoteDeviceDiscoveryAgent = new QBluetoothDeviceDiscoveryAgent(localDevice->address());
// Test if the discovery agent was successfully created
if (remoteDeviceDiscoveryAgent->error() == QBluetoothDeviceDiscoveryAgent::InvalidBluetoothAdapterError) {
ui->dialogStatus->setText(QString("The device discovery agent was not created because the %1 address does not "
"match the physical adapter address of any local Bluetooth device.")
.arg(localDevice->address().toString()));
ui->scan->setEnabled(false);
ui->clear->setEnabled(false);
return;
}
connect(remoteDeviceDiscoveryAgent, SIGNAL(deviceDiscovered(QBluetoothDeviceInfo)),
this, SLOT(addRemoteDevice(QBluetoothDeviceInfo)));
connect(remoteDeviceDiscoveryAgent, SIGNAL(finished()),
this, SLOT(remoteDeviceScanFinished()));
connect(remoteDeviceDiscoveryAgent, SIGNAL(error(QBluetoothDeviceDiscoveryAgent::Error)),
this, SLOT(deviceDiscoveryError(QBluetoothDeviceDiscoveryAgent::Error)));
}
|