simplersble 1.1.1-dev1

The all-in-one Bluetooth library that makes it easy to add wireless connectivity to your projects.
Documentation
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
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
#include "PeripheralLinux.h"

#include "BuildVec.h"
#include "BuilderBase.h"
#include "CharacteristicBase.h"
#include "DescriptorBase.h"
#include "ServiceBase.h"

#include <simpleble/Characteristic.h>
#include <simpleble/Config.h>
#include <simpleble/Descriptor.h>
#include <simpleble/Exceptions.h>
#include <simpleble/Service.h>
#include <simplebluez/Exceptions.h>
#include <algorithm>
#include <thread>
#include "CommonUtils.h"
#include "LoggingInternal.h"

const SimpleBLE::BluetoothUUID BATTERY_SERVICE_UUID = "0000180f-0000-1000-8000-00805f9b34fb";
const SimpleBLE::BluetoothUUID BATTERY_CHARACTERISTIC_UUID = "00002a19-0000-1000-8000-00805f9b34fb";

using namespace SimpleBLE;
using namespace std::chrono_literals;

PeripheralLinux::PeripheralLinux(std::shared_ptr<SimpleBluez::Device> device,
                                 std::shared_ptr<SimpleBluez::Adapter> adapter)
    : device_(std::move(device)), adapter_(std::move(adapter)) {}

PeripheralLinux::~PeripheralLinux() {
    // Clear the callbacks to prevent any further events from being sent to the user.
    this->callback_on_connected_.unload();
    this->callback_on_disconnected_.unload();

    device_->clear_on_connected();
    device_->clear_on_disconnected();
    device_->clear_on_services_resolved();
    _cleanup_characteristics(true);
}

void* PeripheralLinux::underlying() const { return device_.get(); }

std::string PeripheralLinux::identifier() { return device_->name(); }

BluetoothAddress PeripheralLinux::address() { return device_->address(); }

BluetoothAddressType PeripheralLinux::address_type() {
    std::string address_type = device_->address_type();

    if (address_type == "public") {
        return BluetoothAddressType::PUBLIC;
    } else if (address_type == "random") {
        return BluetoothAddressType::RANDOM;
    } else {
        return BluetoothAddressType::UNSPECIFIED;
    }
}

int16_t PeripheralLinux::rssi() { return device_->rssi(); }

int16_t PeripheralLinux::tx_power() { return device_->tx_power(); }

uint16_t PeripheralLinux::mtu() {
    if (!is_connected()) return 0;

    for (auto bluez_service : device_->services()) {
        for (auto bluez_characteristic : bluez_service->characteristics()) {
            // The value provided by Bluez includes an extra 3 bytes from the GATT header
            // which needs to be removed.
            return bluez_characteristic->mtu() - 3;
        }
    }
    return 0;
}

void PeripheralLinux::connect() {
    if (is_connected()) {
        return;
    }

    device_->clear_on_disconnected();
    device_->set_on_connected([this]() { this->connection_cv_.notify_all(); });
    device_->set_on_services_resolved([this]() { this->connection_cv_.notify_all(); });

    // Attempt to connect to the device.
    for (size_t i = 0; i < 5; i++) {
        if (_attempt_connect()) {
            break;
        }
    }

    device_->clear_on_connected();
    device_->clear_on_services_resolved();

    // Set the on_disconnected callback once the connection attempts are finished, thus
    // preventing disconnection events that should not be seen by the user.
    device_->set_on_disconnected([this]() {
        this->_cleanup_characteristics(false);
        this->disconnection_cv_.notify_all();

        SAFE_CALLBACK_CALL(this->callback_on_disconnected_);
    });

    if (!is_connected()) {
        throw Exception::OperationFailed();
    }

    SAFE_CALLBACK_CALL(this->callback_on_connected_);
}

void PeripheralLinux::disconnect() {
    if (!is_connected()) {
        return;
    }

    // Clear the disconnection callback, as most cleanup will be handled manually.
    device_->clear_on_disconnected();

    // Ensure that all characteristics are stopped and cleaned up.
    _cleanup_characteristics(true);

    device_->set_on_disconnected([this]() { this->disconnection_cv_.notify_all(); });

    // Attempt to connect to the device.
    for (size_t i = 0; i < 5; i++) {
        if (_attempt_disconnect()) {
            break;
        }
    }

    if (is_connected()) {
        throw Exception::OperationFailed();
    }

    SAFE_CALLBACK_CALL(this->callback_on_disconnected_);
}

bool PeripheralLinux::is_connected() {
    // NOTE: For Bluez, a device being connected means that it's both
    // connected and services have been resolved.
    return device_->connected() && device_->services_resolved();
}

bool PeripheralLinux::is_connectable() { return device_->name() != ""; }

bool PeripheralLinux::is_paired() { return device_->paired(); }

void PeripheralLinux::unpair() {
    if (device_->paired()) {
        adapter_->device_remove(device_->path());
    }
}

SharedPtrVector<ServiceBase> PeripheralLinux::available_services() {
    bool is_battery_service_available = false;

    SharedPtrVector<ServiceBase> service_list;
    for (auto bluez_service : device_->services()) {
        // Check if the service is the battery service.
        if (bluez_service->uuid() == BATTERY_SERVICE_UUID) {
            is_battery_service_available = true;
        }

        // Build the list of characteristics for the service.
        SharedPtrVector<CharacteristicBase> characteristic_list;
        for (auto bluez_characteristic : bluez_service->characteristics()) {
            // Build the list of descriptors for the characteristic.
            SharedPtrVector<DescriptorBase> descriptor_list;
            for (auto bluez_descriptor : bluez_characteristic->descriptors()) {
                descriptor_list.push_back(std::make_shared<DescriptorBase>(bluez_descriptor->uuid()));
            }

            std::vector<std::string> flags = bluez_characteristic->flags();

            bool can_read = std::find(flags.begin(), flags.end(), "read") != flags.end();
            bool can_write_request = std::find(flags.begin(), flags.end(), "write") != flags.end();
            bool can_write_command = std::find(flags.begin(), flags.end(), "write-without-response") != flags.end();
            bool can_notify = std::find(flags.begin(), flags.end(), "notify") != flags.end();
            bool can_indicate = std::find(flags.begin(), flags.end(), "indicate") != flags.end();

            characteristic_list.push_back(
                std::make_shared<CharacteristicBase>(bluez_characteristic->uuid(), descriptor_list, can_read,
                                                     can_write_request, can_write_command, can_notify, can_indicate));
        }

        service_list.push_back(std::make_shared<ServiceBase>(bluez_service->uuid(), characteristic_list));
    }

    // If the battery service is not available, and the device has the appropriate interface, add it.
    if (!is_battery_service_available && device_->has_battery_interface()) {
        // Emulate the battery service through the Battery1 interface.
        SharedPtrVector<DescriptorBase> descriptor_list;
        SharedPtrVector<CharacteristicBase> characteristic_list = {std::make_shared<CharacteristicBase>(
            BATTERY_CHARACTERISTIC_UUID, descriptor_list, true, false, false, true, false)};
        service_list.push_back(std::make_shared<ServiceBase>(BATTERY_SERVICE_UUID, characteristic_list));
    }

    return service_list;
}

SharedPtrVector<ServiceBase> PeripheralLinux::advertised_services() {
    SharedPtrVector<ServiceBase> service_list;

    auto service_data = device_->service_data();
    for (auto& [service_uuid, data] : service_data) {
        service_list.push_back(std::make_shared<ServiceBase>(service_uuid, data));
    }

    for (auto& service_uuid : device_->uuids()) {
        if (service_data.count(service_uuid) == 0) {
            service_list.push_back(std::make_shared<ServiceBase>(service_uuid));
        }
    }

    return service_list;
}

std::map<uint16_t, ByteArray> PeripheralLinux::manufacturer_data() { return device_->manufacturer_data(); }

ByteArray PeripheralLinux::read(BluetoothUUID const& service, BluetoothUUID const& characteristic) {
    // Check if the user is attempting to read the battery service/characteristic and if so,
    //  emulate the battery service through the Battery1 interface if it's not available.
    if (service == BATTERY_SERVICE_UUID && characteristic == BATTERY_CHARACTERISTIC_UUID &&
        device_->has_battery_interface()) {
        // If this point is reached, the battery service needs to be emulated.
        uint8_t battery_percentage = device_->battery_percentage();
        return ByteArray(reinterpret_cast<char*>(&battery_percentage), 1);
    }

    // Otherwise, attempt to read the characteristic using default mechanisms
    auto char_obj = _get_characteristic(service, characteristic);
    std::vector<std::string> flags = char_obj->flags();
    if (std::find(flags.begin(), flags.end(), "read") == flags.end()) {
        throw Exception::OperationNotSupported("read", characteristic);
    }
    return char_obj->read();
}

void PeripheralLinux::write_request(BluetoothUUID const& service, BluetoothUUID const& characteristic,
                                    ByteArray const& data) {
    // TODO: SimpleBluez::Characteristic::write_request() should also take ByteArray by const reference (but that's
    // another library)
    auto char_obj = _get_characteristic(service, characteristic);
    std::vector<std::string> flags = char_obj->flags();
    if (std::find(flags.begin(), flags.end(), "write") == flags.end()) {
        throw Exception::OperationNotSupported("write_request", characteristic);
    }
    char_obj->write_request(data);
}

void PeripheralLinux::write_command(BluetoothUUID const& service, BluetoothUUID const& characteristic,
                                    ByteArray const& data) {
    // TODO: SimpleBluez::Characteristic::write_command() should also take ByteArray by const reference (but that's
    // another library)
    auto char_obj = _get_characteristic(service, characteristic);
    std::vector<std::string> flags = char_obj->flags();
    if (std::find(flags.begin(), flags.end(), "write-without-response") == flags.end()) {
        throw Exception::OperationNotSupported("write_command", characteristic);
    }
    char_obj->write_command(data);
}

void PeripheralLinux::notify(BluetoothUUID const& service, BluetoothUUID const& characteristic,
                             std::function<void(ByteArray payload)> callback) {
    // Check if the user is attempting to notify the battery service/characteristic and if so,
    //  emulate the battery service through the Battery1 interface if it's not available.
    if (service == BATTERY_SERVICE_UUID && characteristic == BATTERY_CHARACTERISTIC_UUID &&
        device_->has_battery_interface()) {
        // If this point is reached, the battery service needs to be emulated.
        device_->set_on_battery_percentage_changed(
            [callback](uint8_t new_value) { callback(ByteArray(reinterpret_cast<char*>(&new_value), 1)); });
        return;
    }

    // Otherwise, attempt to read the characteristic using default mechanisms
    // TODO: What to do if the characteristic is already being notified?
    auto characteristic_object = _get_characteristic(service, characteristic);
    std::vector<std::string> flags = characteristic_object->flags();
    if (std::find(flags.begin(), flags.end(), "notify") == flags.end() &&
        std::find(flags.begin(), flags.end(), "indicate") == flags.end()) {
        throw Exception::OperationNotSupported("notify", characteristic);
    }
    characteristic_object->set_on_value_changed([callback](SimpleBluez::ByteArray new_value) { callback(new_value); });
    characteristic_object->start_notify();
}

void PeripheralLinux::indicate(BluetoothUUID const& service, BluetoothUUID const& characteristic,
                               std::function<void(ByteArray payload)> callback) {
    notify(service, characteristic, callback);
}

void PeripheralLinux::unsubscribe(BluetoothUUID const& service, BluetoothUUID const& characteristic) {
    // Check if the user is attempting to read the battery service/characteristic and if so,
    //  emulate the battery service through the Battery1 interface if it's not available.
    if (service == BATTERY_SERVICE_UUID && characteristic == BATTERY_CHARACTERISTIC_UUID &&
        device_->has_battery_interface()) {
        // If this point is reached, the battery service needs to be emulated.
        device_->clear_on_battery_percentage_changed();
        return;
    }

    // TODO: What to do if the characteristic is not being notified?
    auto characteristic_object = _get_characteristic(service, characteristic);
    characteristic_object->stop_notify();

    // Wait for the characteristic to stop notifying.
    // TODO: Upgrade SimpleDBus to provide a way to wait for this signal.
    auto timeout = std::chrono::steady_clock::now() + 5s;
    while (characteristic_object->notifying() && std::chrono::steady_clock::now() < timeout) {
        std::this_thread::sleep_for(50ms);
    }
    characteristic_object->clear_on_value_changed();
}

ByteArray PeripheralLinux::read(BluetoothUUID const& service, BluetoothUUID const& characteristic,
                                BluetoothUUID const& descriptor) {
    return _get_descriptor(service, characteristic, descriptor)->read();
}

void PeripheralLinux::write(BluetoothUUID const& service, BluetoothUUID const& characteristic,
                            BluetoothUUID const& descriptor, ByteArray const& data) {
    _get_descriptor(service, characteristic, descriptor)->write(data);
}

void PeripheralLinux::set_callback_on_connected(std::function<void()> on_connected) {
    if (on_connected) {
        callback_on_connected_.load(std::move(on_connected));
    } else {
        callback_on_connected_.unload();
    }
}

void PeripheralLinux::set_callback_on_disconnected(std::function<void()> on_disconnected) {
    if (on_disconnected) {
        callback_on_disconnected_.load(std::move(on_disconnected));
    } else {
        callback_on_disconnected_.unload();
    }
}

// Private methods

void PeripheralLinux::_cleanup_characteristics(bool stop_notifications) noexcept {
    // As this method can be called in multiple stages of a disconnection or object
    // destruction, the entire execution of this method is wrapped in a try-catch
    // block to prevent any exceptions from being thrown, as these will most certainly
    // crash the user application.
    try {
        // Clear all callbacks first to ensure that a failure during `stop_notify`
        // does not leave any dangling callbacks.
        if (device_->has_battery_interface()) {
            device_->clear_on_battery_percentage_changed();
        }

        for (auto bluez_service : device_->services()) {
            for (auto bluez_characteristic : bluez_service->characteristics()) {
                try {
                    bluez_characteristic->clear_on_value_changed();
                } catch (std::exception const& e) {
                    SIMPLEBLE_LOG_WARN(fmt::format("Exception during characteristic cleanup: {}", e.what()));
                }
            }
        }

        if (!stop_notifications || !device_->valid() || !device_->connected()) {
            return;
        }

        // Stop notifying all characteristics while the device is still connected.
        for (auto bluez_service : device_->services()) {
            for (auto bluez_characteristic : bluez_service->characteristics()) {
                try {
                    if (bluez_characteristic->notifying()) {
                        bluez_characteristic->stop_notify();
                    }
                } catch (std::exception const& e) {
                    SIMPLEBLE_LOG_WARN(fmt::format("Exception during characteristic cleanup: {}", e.what()));
                }
            }
        }
    } catch (std::exception const& e) {
        SIMPLEBLE_LOG_WARN(fmt::format("Exception during characteristic cleanup: {}", e.what()));
    } catch (...) {
        // It's possible during the cleanup process that the Bluez device has already
        // been removed, which could cause calls to cleanup methods to throw.
        SIMPLEBLE_LOG_WARN("Unknown exception during characteristic cleanup");
    }
}

bool PeripheralLinux::_attempt_connect() {
    try {
        device_->connect();
    } catch (SimpleDBus::Exception::SendFailed const& e) {
        return false;
    }

    // Wait for the connection to be confirmed.
    // The condition variable will return false if the connection was not established.
    std::unique_lock<std::mutex> lock(connection_mutex_);
    return connection_cv_.wait_for(lock, Config::SimpleBluez::connection_timeout, [this]() { return is_connected(); });
}

bool PeripheralLinux::_attempt_disconnect() {
    device_->disconnect();

    // Wait for the disconnection to be confirmed.
    // The condition variable will return false if the connection is still active.
    std::unique_lock<std::mutex> lock(disconnection_mutex_);
    return disconnection_cv_.wait_for(lock, Config::SimpleBluez::disconnection_timeout,
                                      [this]() { return !is_connected(); });
}

std::shared_ptr<SimpleBluez::Characteristic> PeripheralLinux::_get_characteristic(
    BluetoothUUID const& service_uuid, BluetoothUUID const& characteristic_uuid) {
    try {
        return device_->get_characteristic(service_uuid, characteristic_uuid);
    } catch (SimpleBluez::Exception::ServiceNotFoundException& e) {
        throw Exception::ServiceNotFound(service_uuid);
    } catch (SimpleBluez::Exception::CharacteristicNotFoundException& e) {
        throw Exception::CharacteristicNotFound(characteristic_uuid);
    }
}

std::shared_ptr<SimpleBluez::Descriptor> PeripheralLinux::_get_descriptor(BluetoothUUID const& service_uuid,
                                                                          BluetoothUUID const& characteristic_uuid,
                                                                          BluetoothUUID const& descriptor_uuid) {
    try {
        return device_->get_characteristic(service_uuid, characteristic_uuid)->get_descriptor(descriptor_uuid);
    } catch (SimpleBluez::Exception::ServiceNotFoundException& e) {
        throw Exception::ServiceNotFound(service_uuid);
    } catch (SimpleBluez::Exception::CharacteristicNotFoundException& e) {
        throw Exception::CharacteristicNotFound(characteristic_uuid);
    } catch (SimpleBluez::Exception::DescriptorNotFoundException& e) {
        throw Exception::DescriptorNotFound(descriptor_uuid);
    }
}