forked from DieBieEngineering/DieBieMS-Tool
-
Notifications
You must be signed in to change notification settings - Fork 24
/
bleuart.cpp
301 lines (243 loc) · 9.28 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
/*
Original copyright 2018 Benjamin Vedder benjamin@vedder.se and the VESC Tool project ( https://github.com/vedderb/vesc_tool )
Forked to:
Copyright 2018 Danny Bokma github@diebie.nl (https://github.com/DieBieEngineering/DieBieMS-Tool)
Now forked to:
Copyright 2019 - 2020 Kevin Dionne kevin.dionne@ennoid.me (https://github.com/EnnoidMe/ENNOID-BMS-Tool)
This file is part of ENNOID-BMS Tool.
ENNOID-BMS 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.
ENNOID-BMS 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>
BleUart::BleUart(QObject *parent) : QObject(parent)
{
mControl = 0;
mService = 0;
mUartServiceFound = false;
mConnectDone = false;
mServiceUuid = "6e400001-b5a3-f393-e0a9-e50e24dcca9e";
mRxUuid = "6e400002-b5a3-f393-e0a9-e50e24dcca9e";
mTxUuid = "6e400003-b5a3-f393-e0a9-e50e24dcca9e";
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()));
}
void BleUart::startScan()
{
mDevs.clear();
mDeviceDiscoveryAgent->start();
}
void BleUart::startConnect(QString addr)
{
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));
mControl->setRemoteAddressType(QLowEnergyController::RandomAddress);
#endif
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();
}
void BleUart::disconnectBle()
{
if (mService) {
delete mService;
mService = 0;
}
if (mControl) {
mControl->disconnectFromDevice();
delete mControl;
mControl = 0;
}
}
bool BleUart::isConnected()
{
return mControl != 0 && mConnectDone;
}
bool BleUart::isConnecting()
{
return mControl && !mConnectDone;
}
void BleUart::writeData(QByteArray data)
{
if (isConnected()) {
const QLowEnergyCharacteristic rxChar = mService->characteristic(QBluetoothUuid(QUuid(mRxUuid)));
if (rxChar.isValid()) {
while(data.size() > 20) {
mService->writeCharacteristic(rxChar, data.mid(0, 20),
QLowEnergyService::WriteWithoutResponse);
data.remove(0, 20);
}
mService->writeCharacteristic(rxChar, data, QLowEnergyService::WriteWithoutResponse);
}
}
}
void BleUart::addDevice(const QBluetoothDeviceInfo &dev)
{
if (dev.coreConfigurations() & QBluetoothDeviceInfo::LowEnergyCoreConfiguration) {
qDebug() << "BLE scan found device:" << dev.name();
#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.
mDevs.insert(dev.deviceUuid().toString(), dev.name());
#else
mDevs.insert(dev.address().toString(), dev.name());
#endif
emit scanDone(mDevs, false);
}
}
void BleUart::scanFinished()
{
qDebug() << "BLE scan finished";
emit scanDone(mDevs, true);
}
void BleUart::deviceScanError(QBluetoothDeviceDiscoveryAgent::Error e)
{
qWarning() << "BLE Scan error:" << e;
mDevs.clear();
emit scanDone(mDevs, true);
//emit bleError(tr("BLE Scan error: ") + Utility::QEnumToQString(e));
}
void BleUart::serviceDiscovered(const QBluetoothUuid &gatt)
{
if (gatt==QBluetoothUuid(QUuid(mServiceUuid))){
qDebug() << "BLE UART service found!";
mUartServiceFound = true;
}
}
void BleUart::serviceScanDone()
{
if (mService) {
delete mService;
mService = 0;
}
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(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();
//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::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::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;
// 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";
}