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
393
394
395
396
397
398
399
400
401
402
403
404
|
// Copyright (C) 2022 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
#include "bluezperipheralobjects_p.h"
#include "propertiesadaptor_p.h"
#include "gattservice1adaptor_p.h"
#include "gattcharacteristic1adaptor_p.h"
#include "gattdescriptor1adaptor_p.h"
#include <QtCore/QLoggingCategory>
#include <QtDBus/QDBusConnection>
QT_BEGIN_NAMESPACE
Q_DECLARE_LOGGING_CATEGORY(QT_BT_BLUEZ)
using namespace Qt::StringLiterals;
using namespace QtBluetoothPrivate; // for D-Bus adaptors
static constexpr auto characteristicPathTemplate{"%1/char%2"_L1};
static constexpr auto descriptorPathTemplate{"%1/desc%2"_L1};
static constexpr auto servicePathTemplate{"%1/service%2"_L1};
// The interface names and error values are from BlueZ "gatt-api" documentation
static constexpr auto bluezServiceInterface{"org.bluez.GattService1"_L1};
static constexpr auto bluezCharacteristicInterface{"org.bluez.GattCharacteristic1"_L1};
static constexpr auto bluezDescriptorInterface{"org.bluez.GattDescriptor1"_L1};
static constexpr auto bluezErrorInvalidValueLength{"org.bluez.Error.InvalidValueLength"_L1};
static constexpr auto bluezErrorInvalidOffset{"org.bluez.Error.InvalidOffset"_L1};
static constexpr auto bluezErrorNotAuthorized{"org.bluez.Error.NotAuthorized"_L1};
// Bluetooth Core v5.3, 3.2.9, Vol 3, Part F
static constexpr int maximumAttributeLength{512};
QtBluezPeripheralGattObject::QtBluezPeripheralGattObject(const QString& objectPath,
const QString& uuid, QLowEnergyHandle handle, QObject* parent)
: QObject(parent), objectPath(objectPath), uuid(uuid), handle(handle),
propertiesAdaptor(new OrgFreedesktopDBusPropertiesAdaptor(this))
{}
QtBluezPeripheralGattObject::~QtBluezPeripheralGattObject()
{
unregisterObject();
}
bool QtBluezPeripheralGattObject::registerObject()
{
if (m_registered)
return true;
if (QDBusConnection::systemBus().registerObject(objectPath, this)) {
qCDebug(QT_BT_BLUEZ) << "Registered object on DBus:" << objectPath << uuid;
m_registered = true;
return true;
} else {
qCWarning(QT_BT_BLUEZ) << "Failed to register object on DBus:" << objectPath << uuid;
return false;
}
}
void QtBluezPeripheralGattObject::unregisterObject()
{
if (!m_registered)
return;
QDBusConnection::systemBus().unregisterObject(objectPath);
qCDebug(QT_BT_BLUEZ) << "Unregistered object on DBus:" << objectPath << uuid;
m_registered = false;
}
void QtBluezPeripheralGattObject::accessEvent(const QVariantMap& options)
{
// Report this event for connection management purposes
const auto remoteDevice = options.value("device"_L1).value<QDBusObjectPath>().path();
if (!remoteDevice.isEmpty())
emit remoteDeviceAccessEvent(remoteDevice, options.value("mtu"_L1).toUInt());
}
QtBluezPeripheralDescriptor::QtBluezPeripheralDescriptor(
const QLowEnergyDescriptorData& descriptorData,
const QString& characteristicPath, quint16 ordinal,
QLowEnergyHandle handle, QLowEnergyHandle characteristicHandle,
QObject* parent)
: QtBluezPeripheralGattObject(descriptorPathTemplate.arg(characteristicPath).arg(ordinal),
descriptorData.uuid().toString(QUuid::WithoutBraces), handle, parent),
m_adaptor(new OrgBluezGattDescriptor1Adaptor(this)),
m_characteristicPath(characteristicPath),
m_characteristicHandle(characteristicHandle)
{
if (descriptorData.value().size() > maximumAttributeLength) {
qCWarning(QT_BT_BLUEZ) << "Descriptor value is too large, cropping it to"
<< maximumAttributeLength;
m_value = descriptorData.value().sliced(0, maximumAttributeLength);
} else {
m_value = descriptorData.value();
}
initializeFlags(descriptorData);
}
InterfaceList QtBluezPeripheralDescriptor::properties() const
{
InterfaceList properties;
properties.insert(bluezDescriptorInterface,
{
{"UUID"_L1, uuid},
{"Characteristic"_L1, QDBusObjectPath(m_characteristicPath)},
{"Flags"_L1, m_flags}
});
return properties;
}
// org.bluez.GattDescriptor1
// This function is invoked when remote device reads the value
QByteArray QtBluezPeripheralDescriptor::ReadValue(const QVariantMap &options, QString& error)
{
accessEvent(options);
// Offset is set by Bluez when the value size is more than MTU size.
// Bluez deduces the value size from the first ReadValue. If the
// received data size is larger than MTU, Bluez will take the first MTU bytes and
// issue more ReadValue calls with the 'offset' set
const quint16 offset = options.value("offset"_L1).toUInt();
const quint16 mtu = options.value("mtu"_L1).toUInt();
if (offset > m_value.length() - 1) {
qCWarning(QT_BT_BLUEZ) << "Invalid offset" << offset << ", value len:" << m_value.length();
error = bluezErrorInvalidOffset;
return {};
}
if (offset > 0)
return m_value.mid(offset, mtu);
else
return m_value;
}
// org.bluez.GattDescriptor1
// This function is invoked when remote device writes a value
QString QtBluezPeripheralDescriptor::WriteValue(const QByteArray &value,
const QVariantMap &options)
{
accessEvent(options);
if (options.value("prepare-authorize"_L1).toBool()) {
// Qt API doesn't provide the means for application to authorize
qCWarning(QT_BT_BLUEZ) << "Descriptor write requires authorization."
<< "The client device needs to be trusted beforehand";
return bluezErrorNotAuthorized;
}
if (value.size() > maximumAttributeLength) {
qCWarning(QT_BT_BLUEZ) << "Descriptor value is too large:" << value.size();
return bluezErrorInvalidValueLength;
}
m_value = value;
emit valueUpdatedByRemote(m_characteristicHandle, handle, value);
return {};
}
// This function is called when the value has been updated locally (server-side)
bool QtBluezPeripheralDescriptor::localValueUpdate(const QByteArray& value)
{
if (value.size() > maximumAttributeLength) {
qCWarning(QT_BT_BLUEZ) << "Descriptor value is too large:" << value.size();
return false;
}
m_value = value;
return true;
}
void QtBluezPeripheralDescriptor::initializeFlags(const QLowEnergyDescriptorData& data)
{
// Flag tokens are from org.bluez.GattDescriptor1 documentation
if (data.isReadable())
m_flags.append("read"_L1);
if (data.readConstraints() & QBluetooth::AttAccessConstraint::AttEncryptionRequired)
m_flags.append("encrypt-read"_L1);
if (data.readConstraints() & QBluetooth::AttAccessConstraint::AttAuthenticationRequired)
m_flags.append("encrypt-authenticated-read"_L1);
if (data.isWritable())
m_flags.append("write"_L1);
if (data.writeConstraints() & QBluetooth::AttAccessConstraint::AttEncryptionRequired)
m_flags.append("encrypt-write"_L1);
if (data.writeConstraints() & QBluetooth::AttAccessConstraint::AttAuthenticationRequired)
m_flags.append("encrypt-authenticated-write"_L1);
if (data.readConstraints() & QBluetooth::AttAccessConstraint::AttAuthorizationRequired
|| data.writeConstraints() & QBluetooth::AttAccessConstraint::AttAuthorizationRequired)
m_flags.append("authorize"_L1);
if (m_flags.isEmpty()) {
qCWarning(QT_BT_BLUEZ) << "Descriptor property flags not set" << uuid
<< "Peripheral may fail to register";
}
}
QtBluezPeripheralCharacteristic::QtBluezPeripheralCharacteristic(
const QLowEnergyCharacteristicData& characteristicData,
const QString& servicePath, quint16 ordinal,
QLowEnergyHandle handle, QObject* parent)
: QtBluezPeripheralGattObject(characteristicPathTemplate.arg(servicePath).arg(ordinal),
characteristicData.uuid().toString(QUuid::WithoutBraces), handle, parent),
m_adaptor(new OrgBluezGattCharacteristic1Adaptor(this)),
m_servicePath(servicePath),
m_minimumValueLength(std::min(characteristicData.minimumValueLength(),
maximumAttributeLength)),
m_maximumValueLength(std::min(characteristicData.maximumValueLength(),
maximumAttributeLength))
{
initializeFlags(characteristicData);
initializeValue(characteristicData.value());
}
InterfaceList QtBluezPeripheralCharacteristic::properties() const
{
InterfaceList properties;
properties.insert(bluezCharacteristicInterface,
{
{"UUID"_L1, uuid},
{"Service"_L1, QDBusObjectPath(m_servicePath)},
{"Flags"_L1, m_flags}
});
return properties;
}
// org.bluez.GattCharacteristic1
// This function is invoked when remote device reads the value
QByteArray QtBluezPeripheralCharacteristic::ReadValue(const QVariantMap &options, QString& error)
{
accessEvent(options);
// Offset is set by Bluez when the value size is more than MTU size.
// Bluez deduces the value size from the first ReadValue. If the
// received data size is larger than MTU, Bluez will take the first MTU bytes and
// issue more ReadValue calls with the 'offset' set
const quint16 offset = options.value("offset"_L1).toUInt();
const quint16 mtu = options.value("mtu"_L1).toUInt();
if (offset > m_value.length() - 1) {
qCWarning(QT_BT_BLUEZ) << "Invalid offset" << offset << ", value len:" << m_value.length();
error = bluezErrorInvalidOffset;
return {};
}
if (offset > 0)
return m_value.mid(offset, mtu);
else
return m_value;
}
// org.bluez.GattCharacteristic1
// This function is invoked when remote device writes a value
QString QtBluezPeripheralCharacteristic::WriteValue(const QByteArray &value,
const QVariantMap &options)
{
accessEvent(options);
if (options.value("prepare-authorize"_L1).toBool()) {
// Qt API doesn't provide the means for application to authorize
qCWarning(QT_BT_BLUEZ) << "Characteristic write requires authorization."
<< "The client device needs to be trusted beforehand";
return bluezErrorNotAuthorized;
}
if (value.size() < m_minimumValueLength || value.size() > m_maximumValueLength) {
qCWarning(QT_BT_BLUEZ) << "Characteristic value has invalid length" << value.size()
<< "min:" << m_minimumValueLength
<< "max:" << m_maximumValueLength;
return bluezErrorInvalidValueLength;
}
m_value = value;
emit valueUpdatedByRemote(handle, value);
return {};
}
// This function is called when the value has been updated locally (server-side)
bool QtBluezPeripheralCharacteristic::localValueUpdate(const QByteArray& value)
{
if (value.size() < m_minimumValueLength || value.size() > m_maximumValueLength) {
qCWarning(QT_BT_BLUEZ) << "Characteristic value has invalid length" << value.size()
<< "min:" << m_minimumValueLength
<< "max:" << m_maximumValueLength;
return false;
}
m_value = value;
if (m_notifying) {
emit propertiesAdaptor->PropertiesChanged(
bluezCharacteristicInterface, {{"Value"_L1, m_value}}, {});
}
return true;
}
// org.bluez.GattCharacteristic1
// These are called when remote client enables or disables NTF/IND
void QtBluezPeripheralCharacteristic::StartNotify()
{
qCDebug(QT_BT_BLUEZ) << "NTF or IND enabled for characteristic" << uuid;
m_notifying = true;
}
void QtBluezPeripheralCharacteristic::StopNotify()
{
qCDebug(QT_BT_BLUEZ) << "NTF or IND disabled for characteristic" << uuid;
m_notifying = false;
}
void QtBluezPeripheralCharacteristic::initializeValue(const QByteArray& value)
{
const auto valueSize = value.size();
if (valueSize < m_minimumValueLength || valueSize > m_maximumValueLength) {
qCWarning(QT_BT_BLUEZ) << "Characteristic value has invalid length" << valueSize
<< "min:" << m_minimumValueLength
<< "max:" << m_maximumValueLength;
m_value = QByteArray(m_minimumValueLength, 0);
} else {
m_value = value;
}
}
void QtBluezPeripheralCharacteristic::initializeFlags(const QLowEnergyCharacteristicData& data)
{
// Flag tokens are from org.bluez.GattCharacteristic1 documentation
if (data.properties() & QLowEnergyCharacteristic::PropertyType::Broadcasting)
m_flags.append("broadcast"_L1);
if (data.properties() & QLowEnergyCharacteristic::PropertyType::WriteNoResponse)
m_flags.append("write-without-response"_L1);
if (data.properties() & QLowEnergyCharacteristic::PropertyType::Read)
m_flags.append("read"_L1);
if (data.properties() & QLowEnergyCharacteristic::PropertyType::Write)
m_flags.append("write"_L1);
if (data.properties() & QLowEnergyCharacteristic::PropertyType::Notify)
m_flags.append("notify"_L1);
if (data.properties() & QLowEnergyCharacteristic::PropertyType::Indicate)
m_flags.append("indicate"_L1);
if (data.properties() & QLowEnergyCharacteristic::PropertyType::WriteSigned)
m_flags.append("authenticated-signed-writes"_L1);
if (data.properties() & QLowEnergyCharacteristic::PropertyType::ExtendedProperty) {
// If extended properties property is set, check if we have the descriptor
// describing them. Bluez will generate the actual descriptor based on these
// flags. For clarity: the 'extended-properties' token mentioned in the Bluez
// API is implied by these flags.
for (const auto& descriptor : data.descriptors()) {
// Core Bluetooth v5.3 Vol 3, Part G, 3.3.3.1
if (descriptor.uuid()
== QBluetoothUuid::DescriptorType::CharacteristicExtendedProperties
&& descriptor.value().size() == 2) {
const auto properties = descriptor.value().at(0);
if (properties & 0x01)
m_flags.append("reliable-write"_L1);
if (properties & 0x02)
m_flags.append("writable-auxiliaries"_L1);
}
}
}
if (data.readConstraints() & QBluetooth::AttAccessConstraint::AttEncryptionRequired)
m_flags.append("encrypt-read"_L1);
if (data.readConstraints() & QBluetooth::AttAccessConstraint::AttAuthenticationRequired)
m_flags.append("encrypt-authenticated-read"_L1);
if (data.writeConstraints() & QBluetooth::AttAccessConstraint::AttEncryptionRequired)
m_flags.append("encrypt-write"_L1);
if (data.writeConstraints() & QBluetooth::AttAccessConstraint::AttAuthenticationRequired)
m_flags.append("encrypt-authenticated-write"_L1);
if (data.readConstraints() & QBluetooth::AttAccessConstraint::AttAuthorizationRequired
|| data.writeConstraints() & QBluetooth::AttAccessConstraint::AttAuthorizationRequired)
m_flags.append("authorize"_L1);
if (m_flags.isEmpty()) {
qCWarning(QT_BT_BLUEZ) << "Characteristic property flags not set" << uuid
<< "Peripheral may fail to register";
}
}
QtBluezPeripheralService::QtBluezPeripheralService(const QLowEnergyServiceData &serviceData,
const QString& applicationPath, quint16 ordinal,
QLowEnergyHandle handle, QObject* parent)
: QtBluezPeripheralGattObject(servicePathTemplate.arg(applicationPath).arg(ordinal),
serviceData.uuid().toString(QUuid::WithoutBraces), handle, parent),
m_isPrimary(serviceData.type() == QLowEnergyServiceData::ServiceTypePrimary),
m_adaptor(new OrgBluezGattService1Adaptor(this))
{
}
void QtBluezPeripheralService::addIncludedService(const QString& objectPath) {
qCDebug(QT_BT_BLUEZ) << "Adding included service" << objectPath << "for" << uuid;
m_includedServices.append(QDBusObjectPath(objectPath));
}
InterfaceList QtBluezPeripheralService::properties() const {
InterfaceList interfaces;
interfaces.insert(bluezServiceInterface,{
{"UUID"_L1, uuid},
{"Primary"_L1, m_isPrimary},
{"Includes"_L1, QVariant::fromValue(m_includedServices)}
});
return interfaces;
};
QT_END_NAMESPACE
#include "moc_bluezperipheralobjects_p.cpp"
|