forked from vedderb/bldc-tool
-
Notifications
You must be signed in to change notification settings - Fork 0
/
bleinterface.cpp
323 lines (286 loc) · 11 KB
/
bleinterface.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
#include "bleinterface.h"
#include <QDebug>
#include <QEventLoop>
DeviceInfo::DeviceInfo(const QBluetoothDeviceInfo &info):
QObject(), m_device(info)
{
}
QBluetoothDeviceInfo DeviceInfo::getDevice() const
{
return m_device;
}
QString DeviceInfo::getAddress() const
{
#ifdef Q_OS_MAC
// workaround for Core Bluetooth:
return m_device.deviceUuid().toString();
#else
return m_device.address().toString();
#endif
}
void DeviceInfo::setDevice(const QBluetoothDeviceInfo &device)
{
m_device = device;
emit deviceChanged();
}
BLEInterface::BLEInterface(QObject *parent) : QObject(parent),
m_currentDevice(0),
m_control(0),
m_service(0),
m_readTimer(0),
m_connected(false),
m_serviceUuid(SERVICE_UUID)
{
m_deviceDiscoveryAgent = new QBluetoothDeviceDiscoveryAgent(this);
connect(m_deviceDiscoveryAgent, SIGNAL(deviceDiscovered(const QBluetoothDeviceInfo&)),
this, SLOT(addDevice(const QBluetoothDeviceInfo&)));
connect(m_deviceDiscoveryAgent, SIGNAL(error(QBluetoothDeviceDiscoveryAgent::Error)),
this, SLOT(onDeviceScanError(QBluetoothDeviceDiscoveryAgent::Error)));
connect(m_deviceDiscoveryAgent, SIGNAL(finished()), this, SLOT(onScanFinished()));
m_deviceDiscoveryAgent->start();
}
BLEInterface::~BLEInterface()
{
qDeleteAll(m_devices);
m_devices.clear();
}
void BLEInterface::scanDevices()
{
m_devicesNames.clear();
qDeleteAll(m_devices);
m_devices.clear();
emit devicesNamesChanged(m_devicesNames);
m_deviceDiscoveryAgent->start();
emit statusInfoChanged("Scanning for devices...", true);
}
void BLEInterface::read(){
if(m_service && m_readCharacteristic.isValid())
m_service->readCharacteristic(m_readCharacteristic);
}
void BLEInterface::waitForWrite(){
QEventLoop pause;
connect(m_service, &QLowEnergyService::characteristicWritten,
&pause, &QEventLoop::quit);
connect(m_service, SIGNAL(error(QLowEnergyService::ServiceError)),
&pause, SLOT(quit()));
pause.exec();
}
void BLEInterface::write(const QByteArray &data)
{
qDebug() << "BLEInterface::write: " << data;
if(m_service && m_writeCharacteristic.isValid()){
if(data.length() > CHUNK_SIZE){
int sentBytes = 0;
while (sentBytes < data.length()) {
m_service->writeCharacteristic(m_writeCharacteristic,
data.mid(sentBytes, CHUNK_SIZE),
m_writeMode);
sentBytes += CHUNK_SIZE;
if(m_writeMode == QLowEnergyService::WriteWithResponse){
waitForWrite();
if(m_service->error() != QLowEnergyService::NoError)
break;
}
}
}
else
m_service->writeCharacteristic(m_writeCharacteristic, data, m_writeMode);
}
}
void BLEInterface::addDevice(const QBluetoothDeviceInfo &device)
{
if (device.coreConfigurations() & QBluetoothDeviceInfo::LowEnergyCoreConfiguration) {
qWarning() << "Discovered LE Device name: " << device.name() << " Address: "
<< device.address().toString();
m_devicesNames.append(device.name());
DeviceInfo *dev = new DeviceInfo(device);
m_devices.append(dev);
emit devicesNamesChanged(m_devicesNames);
emit statusInfoChanged("Low Energy device found", true);
}
//...
}
void BLEInterface::onScanFinished()
{
if (m_devicesNames.size() == 0)
emit statusInfoChanged("No Low Energy devices found", false);
}
void BLEInterface::onDeviceScanError(QBluetoothDeviceDiscoveryAgent::Error error)
{
if (error == QBluetoothDeviceDiscoveryAgent::PoweredOffError)
emit statusInfoChanged("The Bluetooth adaptor is powered off, power it on before doing discovery.", false);
else if (error == QBluetoothDeviceDiscoveryAgent::InputOutputError)
emit statusInfoChanged("Writing or reading from the device resulted in an error.", false);
else
emit statusInfoChanged("An unknown error has occurred.", false);
}
void BLEInterface::connectCurrentDevice()
{
if(m_devices.isEmpty())
return;
if (m_control) {
m_control->disconnectFromDevice();
delete m_control;
m_control = 0;
}
m_control = new QLowEnergyController(m_devices[ m_currentDevice]->getDevice(), this);
connect(m_control, SIGNAL(serviceDiscovered(QBluetoothUuid)),
this, SLOT(onServiceDiscovered(QBluetoothUuid)));
connect(m_control, SIGNAL(discoveryFinished()),
this, SLOT(onServiceScanDone()));
connect(m_control, SIGNAL(error(QLowEnergyController::Error)),
this, SLOT(onControllerError(QLowEnergyController::Error)));
connect(m_control, SIGNAL(connected()),
this, SLOT(onDeviceConnected()));
connect(m_control, SIGNAL(disconnected()),
this, SLOT(onDeviceDisconnected()));
m_control->connectToDevice();
}
void BLEInterface::onDeviceConnected()
{
m_control->discoverServices();
}
void BLEInterface::onDeviceDisconnected()
{
update_connected(false);
emit statusInfoChanged("Service disconnected", false);
qWarning() << "Remote device disconnected";
}
void BLEInterface::onServiceDiscovered(const QBluetoothUuid &gatt)
{
if(gatt == m_serviceUuid){
emit statusInfoChanged("Service discovered. Waiting for service scan to be done...", true);
m_foundService = true;
}
}
void BLEInterface::onServiceScanDone()
{
delete m_service;
m_service = 0;
if (m_foundService) {
m_service = m_control->createServiceObject(
m_serviceUuid, this);
}
if (!m_service) {
emit statusInfoChanged("Service not found.", false);
return;
}
connect(m_service, SIGNAL(stateChanged(QLowEnergyService::ServiceState)),
this, SLOT(onServiceStateChanged(QLowEnergyService::ServiceState)));
connect(m_service, SIGNAL(characteristicChanged(QLowEnergyCharacteristic,QByteArray)),
this, SLOT(onCharacteristicChanged(QLowEnergyCharacteristic,QByteArray)));
connect(m_service, SIGNAL(characteristicRead(QLowEnergyCharacteristic,QByteArray)),
this, SLOT(onCharacteristicRead(QLowEnergyCharacteristic,QByteArray)));
connect(m_service, SIGNAL(characteristicWritten(QLowEnergyCharacteristic,QByteArray)),
this, SLOT(onCharacteristicWrite(QLowEnergyCharacteristic,QByteArray)));
connect(m_service, SIGNAL(error(QLowEnergyService::ServiceError)),
this, SLOT(serviceError(QLowEnergyService::ServiceError)));
if(m_service->state() == QLowEnergyService::DiscoveryRequired) {
emit statusInfoChanged("Connecting to service...", true);
m_service->discoverDetails();
}
else
searchCharacteristic();
}
void BLEInterface::disconnectDevice()
{
m_foundService = false;
m_readTimer->deleteLater();
m_readTimer = NULL;
if (m_devices.isEmpty()) {
return;
}
//disable notifications
if (m_notificationDesc.isValid() && m_service) {
m_service->writeDescriptor(m_notificationDesc, QByteArray::fromHex("0000"));
} else {
m_control->disconnectFromDevice();
delete m_service;
m_service = 0;
}
}
void BLEInterface::onControllerError(QLowEnergyController::Error error)
{
emit statusInfoChanged("Cannot connect to remote device.", false);
qWarning() << "Controller Error:" << error;
}
void BLEInterface::onCharacteristicChanged(const QLowEnergyCharacteristic &c,
const QByteArray &value)
{
Q_UNUSED(c)
qDebug() << "Characteristic Changed: " << value;
emit dataReceived(value);
}
void BLEInterface::onCharacteristicWrite(const QLowEnergyCharacteristic &c,
const QByteArray &value)
{
Q_UNUSED(c)
qDebug() << "Characteristic Written: " << value;
}
void BLEInterface::onCharacteristicRead(const QLowEnergyCharacteristic &c,
const QByteArray &value){
Q_UNUSED(c)
qDebug() << "Characteristic Read: " << value;
emit dataReceived(value);
}
void BLEInterface::searchCharacteristic(){
if(m_service){
QMap<QLowEnergyCharacteristic::PropertyTypes, QLowEnergyCharacteristic> properties;
foreach (QLowEnergyCharacteristic c, m_service->characteristics()) {
if(c.isValid()){
if (c.properties() & QLowEnergyCharacteristic::WriteNoResponse){
properties[QLowEnergyCharacteristic::WriteNoResponse] = c;
}
if(c.properties() & QLowEnergyCharacteristic::Write) {
properties[QLowEnergyCharacteristic::Write] = c;
}
if (c.properties() & QLowEnergyCharacteristic::Read) {
properties[QLowEnergyCharacteristic::Read] = c;
}
if (c.properties() & QLowEnergyCharacteristic::Notify) {
properties[QLowEnergyCharacteristic::Notify] = c;
m_notificationDesc = c.descriptor(
QBluetoothUuid::ClientCharacteristicConfiguration);
if (m_notificationDesc.isValid()) {
m_service->writeDescriptor(m_notificationDesc, QByteArray::fromHex("0100"));
}
}
}
}
bool valid = ( properties.contains(QLowEnergyCharacteristic::WriteNoResponse) ||
properties.contains(QLowEnergyCharacteristic::Write)) &&
(properties.contains(QLowEnergyCharacteristic::Notify) ||
properties.contains(QLowEnergyCharacteristic::Read));
if(valid){
if(!properties.contains(QLowEnergyCharacteristic::Notify) &&
properties.contains(QLowEnergyCharacteristic::Read)){
m_readCharacteristic = properties[QLowEnergyCharacteristic::Read];
if(!m_readTimer){
m_readTimer = new QTimer(this);
connect(m_readTimer, &QTimer::timeout, this, &BLEInterface::read);
m_readTimer->start(READ_INTERVAL_MS);
}
}
if(properties.contains(QLowEnergyCharacteristic::Write)){
m_writeCharacteristic = properties[QLowEnergyCharacteristic::Write];
m_writeMode = QLowEnergyService::WriteWithResponse;
}
else if(properties.contains(QLowEnergyCharacteristic::WriteNoResponse)){
m_writeCharacteristic = properties[QLowEnergyCharacteristic::WriteNoResponse];
m_writeMode = QLowEnergyService::WriteWithoutResponse;
}
update_connected(true);
}
}
}
void BLEInterface::onServiceStateChanged(QLowEnergyService::ServiceState s)
{
qDebug() << "serviceStateChanged, state: " << s;
if (s == QLowEnergyService::ServiceDiscovered) {
searchCharacteristic();
}
}
void BLEInterface::serviceError(QLowEnergyService::ServiceError e)
{
qWarning() << "Service error:" << e;
}