-
Notifications
You must be signed in to change notification settings - Fork 524
/
bleuart.cpp
392 lines (324 loc) · 11.6 KB
/
bleuart.cpp
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
380
381
382
383
384
385
386
387
388
389
390
391
392
/*
Copyright 2017 Benjamin Vedder [email protected]
This file is part of VESC Tool.
VESC Tool is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
VESC Tool is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "bleuart.h"
#include "utility.h"
#include <QDebug>
#include <QLowEnergyConnectionParameters>
#include <QSettings>
BleUart::BleUart(QObject *parent) : QObject(parent)
{
mControl = nullptr;
mService = nullptr;
mUartServiceFound = false;
mConnectDone = false;
mScanFinished = true;
mInitDone = false;
mServiceUuid = "6e400001-b5a3-f393-e0a9-e50e24dcca9e";
mRxUuid = "6e400002-b5a3-f393-e0a9-e50e24dcca9e";
mTxUuid = "6e400003-b5a3-f393-e0a9-e50e24dcca9e";
}
BleUart::~BleUart() {
if (mService) {
delete mService;
mService = nullptr;
}
if (mControl) {
delete mControl;
mControl = nullptr;
}
}
void BleUart::startScan()
{
init();
mDevs.clear();
mDeviceDiscoveryAgent->start(QBluetoothDeviceDiscoveryAgent::LowEnergyMethod);
mScanFinished = false;
}
void BleUart::startConnect(QString addr)
{
init();
disconnectBle();
mUartServiceFound = false;
mConnectDone = false;
#if defined(Q_OS_MACOS) || defined(Q_OS_IOS)
// Create BT Controller from unique device UUID stored as addr. Creating
// a controller using a devices address is not supported on macOS or iOS.
QBluetoothDeviceInfo deviceInfo = QBluetoothDeviceInfo();
deviceInfo.setDeviceUuid(QBluetoothUuid(addr));
mControl = new QLowEnergyController(deviceInfo);
#else
mControl = new QLowEnergyController(QBluetoothAddress(addr));
#endif
mControl->setRemoteAddressType(QLowEnergyController::RandomAddress);
connect(mControl, SIGNAL(serviceDiscovered(QBluetoothUuid)),
this, SLOT(serviceDiscovered(QBluetoothUuid)));
connect(mControl, SIGNAL(discoveryFinished()),
this, SLOT(serviceScanDone()));
connect(mControl, SIGNAL(error(QLowEnergyController::Error)),
this, SLOT(controllerError(QLowEnergyController::Error)));
connect(mControl, SIGNAL(connected()),
this, SLOT(deviceConnected()));
connect(mControl, SIGNAL(disconnected()),
this, SLOT(deviceDisconnected()));
connect(mControl, SIGNAL(stateChanged(QLowEnergyController::ControllerState)),
this, SLOT(controlStateChanged(QLowEnergyController::ControllerState)));
connect(mControl, SIGNAL(connectionUpdated(QLowEnergyConnectionParameters)),
this, SLOT(connectionUpdated(QLowEnergyConnectionParameters)));
mControl->connectToDevice();
mConnectTimeoutTimer.start(10000);
}
void BleUart::disconnectBle()
{
init();
if (mService) {
mService->deleteLater();
mService = nullptr;
}
if (mControl) {
mControl->deleteLater();
mControl = nullptr;
}
}
bool BleUart::isConnected()
{
return mControl != nullptr && mConnectDone;
}
bool BleUart::isConnecting()
{
return mControl && !mConnectDone;
}
void BleUart::emitScanDone()
{
mConnectTimeoutTimer.stop();
emit scanDone(mDevs, mScanFinished);
}
void BleUart::writeData(QByteArray data)
{
if (isConnected()) {
const QLowEnergyCharacteristic rxChar = mService->characteristic(QBluetoothUuid(QUuid(mRxUuid)));
if (rxChar.isValid()) {
int chunk = 20;
while(data.size() > chunk) {
mService->writeCharacteristic(rxChar, data.mid(0, chunk),
QLowEnergyService::WriteWithoutResponse);
data.remove(0, chunk);
}
mService->writeCharacteristic(rxChar, data, QLowEnergyService::WriteWithoutResponse);
}
}
}
void BleUart::addDevice(const QBluetoothDeviceInfo &dev)
{
if ((dev.coreConfigurations() & QBluetoothDeviceInfo::LowEnergyCoreConfiguration)) {
qDebug() << "BLE scan found device:" << dev.name() <<
"Valid:" << dev.isValid() <<
"Cached:" << dev.isCached() <<
"rssi:" << dev.rssi();
#if defined(Q_OS_MACOS) || defined(Q_OS_IOS)
// macOS and iOS do not expose the hardware address of BLTE devices, must use
// the OS generated UUID.
QString addr = dev.deviceUuid().toString();
#else
QString addr = dev.address().toString();
#endif
bool preferred = false;
{
QSettings set;
int size = set.beginReadArray("blePreferred");
for (int i = 0; i < size; ++i) {
set.setArrayIndex(i);
QString address = set.value("address").toString();
bool pref = set.value("preferred").toBool();
if (addr == address && pref) {
preferred = true;
}
}
set.endArray();
}
#if defined(Q_OS_WIN)
mDevs.insert(addr, dev.name());
#else
if(preferred || dev.serviceUuids().contains(QBluetoothUuid(QUuid("6e400001-b5a3-f393-e0a9-e50e24dcca9e")))) {
mDevs.insert(addr, dev.name());
}
#endif
mConnectTimeoutTimer.stop();
emit scanDone(mDevs, false);
}
}
void BleUart::scanFinished()
{
qDebug() << "BLE scan finished";
mScanFinished = true;
mConnectTimeoutTimer.stop();
emit scanDone(mDevs, true);
}
void BleUart::deviceScanError(QBluetoothDeviceDiscoveryAgent::Error e)
{
qWarning() << "BLE Scan error: " << e;
mDevs.clear();
mScanFinished = true;
emit scanDone(mDevs, true);
QString errorStr = tr("BLE Scan error: ") + Utility::QEnumToQString(e);
#ifdef Q_OS_ANDROID
errorStr += ". If you are on Android 10, make sure that both bluetooth and the "
"location service are activated.";
#endif
mConnectTimeoutTimer.stop();
emit bleError(errorStr);
}
void BleUart::serviceDiscovered(const QBluetoothUuid &gatt)
{
if (gatt==QBluetoothUuid(QUuid(mServiceUuid))){
qDebug() << "BLE UART service found!";
mUartServiceFound = true;
}
}
void BleUart::serviceScanDone()
{
if (mService) {
mService->deleteLater();
mService = nullptr;
}
if (mUartServiceFound) {
qDebug() << "Connecting to BLE UART service";
mService = mControl->createServiceObject(QBluetoothUuid(QUuid(mServiceUuid)), this);
connect(mService, SIGNAL(stateChanged(QLowEnergyService::ServiceState)),
this, SLOT(serviceStateChanged(QLowEnergyService::ServiceState)));
connect(mService, SIGNAL(error(QLowEnergyService::ServiceError)),
this, SLOT(serviceError(QLowEnergyService::ServiceError)));
connect(mService, SIGNAL(characteristicChanged(QLowEnergyCharacteristic,QByteArray)),
this, SLOT(updateData(QLowEnergyCharacteristic,QByteArray)));
connect(mService, SIGNAL(descriptorWritten(QLowEnergyDescriptor,QByteArray)),
this, SLOT(confirmedDescriptorWrite(QLowEnergyDescriptor,QByteArray)));
mService->discoverDetails();
} else {
qWarning() << "BLE UART service not found";
disconnectBle();
}
}
void BleUart::controllerError(QLowEnergyController::Error e)
{
qWarning() << "BLE error:" << e;
disconnectBle();
mConnectTimeoutTimer.stop();
emit bleError(tr("BLE error: ") + Utility::QEnumToQString(e));
}
void BleUart::deviceConnected()
{
qDebug() << "BLE device connected";
mControl->discoverServices();
}
void BleUart::deviceDisconnected()
{
qDebug() << "BLE service disconnected";
disconnectBle();
}
void BleUart::serviceStateChanged(QLowEnergyService::ServiceState s)
{
// A descriptor can only be written if the service is in the ServiceDiscovered state
switch (s) {
case QLowEnergyService::InvalidService: {
//this gets triggered when a connected device is shutoff or goes out of BLE range
qDebug() << "device disconnected unintentionally";
emit unintentionalDisconnect();
break;
}
case QLowEnergyService::ServiceDiscovered: {
//looking for the TX characteristic
const QLowEnergyCharacteristic txChar = mService->characteristic(
QBluetoothUuid(QUuid(mTxUuid)));
if (!txChar.isValid()){
qDebug() << "BLE Tx characteristic not found";
break;
}
//looking for the RX characteristic
const QLowEnergyCharacteristic rxChar = mService->characteristic(QBluetoothUuid(QUuid(mRxUuid)));
if (!rxChar.isValid()) {
qDebug() << "BLE Rx characteristic not found";
break;
}
// Bluetooth LE spec Where a characteristic can be notified, a Client Characteristic Configuration descriptor
// shall be included in that characteristic as required by the Bluetooth Core Specification
// Tx notify is enabled
mNotificationDescTx = txChar.descriptor(QBluetoothUuid::ClientCharacteristicConfiguration);
if (mNotificationDescTx.isValid()) {
// enable notification
mService->writeDescriptor(mNotificationDescTx, QByteArray::fromHex("0100"));
}
break;
}
default:
break;
}
}
void BleUart::serviceError(QLowEnergyService::ServiceError e){
qDebug() << e;
}
void BleUart::updateData(const QLowEnergyCharacteristic &c, const QByteArray &value)
{
if (c.uuid() == QBluetoothUuid(QUuid(mTxUuid))) {
emit dataRx(value);
}
}
void BleUart::confirmedDescriptorWrite(const QLowEnergyDescriptor &d, const QByteArray &value)
{
if (d.isValid() && d == mNotificationDescTx && value == QByteArray("0000")) {
//disabled notifications -> assume disconnect intent
disconnectBle();
} else {
mConnectDone = true;
mConnectTimeoutTimer.stop();
emit connected();
}
}
void BleUart::controlStateChanged(QLowEnergyController::ControllerState state)
{
(void)state;
// qDebug() << state;
// if (state == QLowEnergyController::ConnectedState) {
// QLowEnergyConnectionParameters param;
// param.setIntervalRange(7.5, 7.5);
// param.setSupervisionTimeout(10000);
// param.setLatency(0);
// mControl->requestConnectionUpdate(param);
// }
}
void BleUart::connectionUpdated(const QLowEnergyConnectionParameters &newParameters)
{
(void)newParameters;
qDebug() << "BLE connection parameters updated";
}
void BleUart::init()
{
if (mInitDone) {
return;
}
Utility::requestBleScanPermission();
Utility::requestBleConnectPermission();
mDeviceDiscoveryAgent = new QBluetoothDeviceDiscoveryAgent(this);
connect(mDeviceDiscoveryAgent, SIGNAL(deviceDiscovered(const QBluetoothDeviceInfo&)),
this, SLOT(addDevice(const QBluetoothDeviceInfo&)));
connect(mDeviceDiscoveryAgent, SIGNAL(error(QBluetoothDeviceDiscoveryAgent::Error)),
this, SLOT(deviceScanError(QBluetoothDeviceDiscoveryAgent::Error)));
connect(mDeviceDiscoveryAgent, SIGNAL(finished()), this, SLOT(scanFinished()));
mInitDone = true;
mConnectTimeoutTimer.setSingleShot(true);
connect(&mConnectTimeoutTimer, &QTimer::timeout, [this]() {
disconnectBle();
qDebug() << "BLE connect timeout";
emit bleError(tr("BLE connect timed out."));
});
}