simplersble 1.0.1-dev25

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
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
// This weird pragma is required for the compiler to properly include the necessary namespaces.
#pragma comment(lib, "windowsapp")

#include "PeripheralWindows.h"
#include "CommonUtils.h"
#include "Utils.h"
#include "MtaManager.h"
#include "BackendWinRT.h"

#include "../common/CharacteristicBase.h"
#include "../common/DescriptorBase.h"
#include "../common/ServiceBase.h"
#include "simpleble/Characteristic.h"
#include "simpleble/Descriptor.h"
#include "simpleble/Service.h"

#include <simpleble/Exceptions.h>
#include <simpleble/Config.h>

#include "winrt/Windows.Foundation.Collections.h"
#include "winrt/Windows.Foundation.h"
#include "winrt/Windows.Devices.Enumeration.h"
#include "winrt/Windows.Storage.Streams.h"
#include "winrt/base.h"

#include <iostream>

using namespace SimpleBLE;
using namespace SimpleBLE::WinRT;
using namespace std::chrono_literals;

PeripheralWindows::PeripheralWindows(BluetoothLEDevice device) {
    device_ = device;
    identifier_ = winrt::to_string(device.Name());
    address_ = _mac_address_to_str(device.BluetoothAddress());
    address_type_ = BluetoothAddressType::PUBLIC;

    // NOTE: We're assuming that the device is connectable, as this constructor is only called
    // when the device has paired in the past.
    connectable_ = true;
}

PeripheralWindows::PeripheralWindows(advertising_data_t advertising_data) {
    address_type_ = advertising_data.address_type;
    identifier_ = advertising_data.identifier;
    address_ = advertising_data.mac_address;
    rssi_ = advertising_data.rssi;
    tx_power_ = advertising_data.tx_power;
    manufacturer_data_ = advertising_data.manufacturer_data;
    service_data_ = advertising_data.service_data;
    connectable_ = advertising_data.connectable;
}

PeripheralWindows::~PeripheralWindows() {
    if (connection_status_changed_token_ && device_ != nullptr) {
        MtaManager::get().execute_sync([this]() {
            device_.ConnectionStatusChanged(connection_status_changed_token_);
        });
    }
}

void* PeripheralWindows::underlying() const {
    return reinterpret_cast<void*>(const_cast<BluetoothLEDevice*>(&device_));
}

SimpleBLE::BluetoothAddressType PeripheralWindows::address_type() { return address_type_; }

std::string PeripheralWindows::identifier() { return identifier_; }

BluetoothAddress PeripheralWindows::address() { return address_; }

int16_t PeripheralWindows::rssi() { return rssi_; }

int16_t PeripheralWindows::tx_power() { return tx_power_; }

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

    // The value provided by the MaxPduSize includes an extra 3 bytes from the GATT header
    // which needs to be removed.
    return mtu_ - 3;
}

void PeripheralWindows::update_advertising_data(advertising_data_t advertising_data) {
    if (advertising_data.identifier != "") {
        identifier_ = advertising_data.identifier;
    }
    rssi_ = advertising_data.rssi;
    tx_power_ = advertising_data.tx_power;
    address_type_ = advertising_data.address_type;
    manufacturer_data_ = advertising_data.manufacturer_data;

    advertising_data.service_data.merge(service_data_);
    service_data_ = advertising_data.service_data;
}

bool PeripheralWindows::is_disconnect_pending() const noexcept {
    return SimpleBLE::Config::WinRT::use_deferred_disconnect &&
           connection_state_ == ConnectionState::Disconnecting;
}

void PeripheralWindows::connect() {
    if (!BackendWinRT::get()->bluetooth_enabled()) {
        throw SimpleBLE::Exception::OperationFailed("Bluetooth is not enabled.");
    }

    if (SimpleBLE::Config::WinRT::use_deferred_disconnect) {
        if (connection_state_ == ConnectionState::Disconnecting) {
            throw SimpleBLE::Exception::OperationFailed("Device is still disconnecting");
        }
        connection_state_ = ConnectionState::Connecting;
    }

    MtaManager::get().execute_sync([this]() {
        device_ = async_get(BluetoothLEDevice::FromBluetoothAddressAsync(_str_to_mac_address(address_)));
    });

    if (device_ == nullptr) {
        if (SimpleBLE::Config::WinRT::use_deferred_disconnect) {
            connection_state_ = ConnectionState::Disconnected;
        }
        throw SimpleBLE::Exception::OperationFailed("Failed to retrieve Bluetooth device.");
    }

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

    if (is_connected()) {
        callback_on_disconnected_pending_.store(true);

        MtaManager::get().execute_sync([this]() {
            connection_status_changed_token_ = device_.ConnectionStatusChanged(
                [this](const BluetoothLEDevice device, const auto args) {
                    if (device.ConnectionStatus() == BluetoothConnectionStatus::Disconnected) {
                        if (SimpleBLE::Config::WinRT::use_deferred_disconnect) {
                            connection_state_ = ConnectionState::Disconnected;
                            
                            // Explicitly clean up WinRT service objects and clear the map
                            // on a spontaneous disconnect to prevent stale sessions leaking.
                            for (auto& [uuid, svc] : gatt_map_) {
                                if (svc.obj) svc.obj.Close();
                            }
                            gatt_map_.clear();
                            
                            device_ = nullptr;
                        }
                        this->disconnection_cv_.notify_all();

                        if (callback_on_disconnected_pending_.exchange(false)) {
                            SAFE_CALLBACK_CALL(this->callback_on_disconnected_);
                        }
                    }
                });
        });

        if (SimpleBLE::Config::WinRT::use_deferred_disconnect) {
            connection_state_ = ConnectionState::Connected;
        }
        SAFE_CALLBACK_CALL(this->callback_on_connected_);
    } else {
        if (SimpleBLE::Config::WinRT::use_deferred_disconnect) {
            connection_state_ = ConnectionState::Disconnected;
        }
        throw SimpleBLE::Exception::OperationFailed("Failed to connect to device.");
    }
}

void PeripheralWindows::disconnect() {
    if (device_ == nullptr) {
        if (SimpleBLE::Config::WinRT::use_deferred_disconnect) {
            connection_state_ = ConnectionState::Disconnected;
        }
        return;
    }

    if (SimpleBLE::Config::WinRT::use_deferred_disconnect) {
        // Deferred path
        if (connection_state_ == ConnectionState::Disconnecting ||
            connection_state_ == ConnectionState::Disconnected) {
            return;
        }

        connection_state_ = ConnectionState::Disconnecting;

        // Explicitly close services (extra safety against stale WinRT objects)
        for (auto& [uuid, svc] : gatt_map_) {
            if (svc.obj) svc.obj.Close();
        }
        gatt_map_.clear();

        MtaManager::get().execute_sync([this]() {
            device_.Close();   // fire-and-forget – the 3 s delay still happens in background
        });
    } else {
        // Blocking path
        gatt_map_.clear();
        MtaManager::get().execute_sync([this]() {
            device_.Close();
        });

        std::unique_lock<std::mutex> lock(disconnection_mutex_);
        if (disconnection_cv_.wait_for(lock, 10s, [this] { return !this->is_connected(); })) {
            // Disconnection successful
        } else {
            SIMPLEBLE_LOG_ERROR("Disconnection failed");
            throw SimpleBLE::Exception::OperationFailed("Disconnection attempt was not acknowledged.");
        }

        device_ = nullptr;
    }

    if (callback_on_disconnected_pending_.exchange(false)) {
        SAFE_CALLBACK_CALL(this->callback_on_disconnected_);
    }
}

bool PeripheralWindows::is_connected() {
    if (device_ == nullptr) {
        return false;
    }

    if (SimpleBLE::Config::WinRT::use_deferred_disconnect) {
        if (connection_state_ == ConnectionState::Disconnecting ||
            connection_state_ == ConnectionState::Disconnected) {
            return false;
        }
    }

    return MtaManager::get().execute_sync<bool>([this]() {
        return device_.ConnectionStatus() == BluetoothConnectionStatus::Connected;
    });
}

bool PeripheralWindows::is_connectable() { return connectable_; }

bool PeripheralWindows::is_paired() {
    const BluetoothAddress target_address = address_;
    const winrt::hstring aqs_filter = BluetoothLEDevice::GetDeviceSelectorFromPairingState(true);

    return MtaManager::get().execute_sync<bool>([target_address, aqs_filter]() {
        auto dev_info_collection = async_get(Devices::Enumeration::DeviceInformation::FindAllAsync(aqs_filter));

        for (const auto& dev_info : dev_info_collection) {
            if (_bluetooth_address_from_id(winrt::to_string(dev_info.Id())) == target_address) {
                return true;
            }
        }

        return false;
    });
}

void PeripheralWindows::unpair() { throw Exception::OperationNotSupported(); }

SharedPtrVector<ServiceBase> PeripheralWindows::available_services() {
    SharedPtrVector<ServiceBase> service_list;
    for (auto& [service_uuid, service] : gatt_map_) {
        // Build the list of characteristics for the service.
        SharedPtrVector<CharacteristicBase> characteristic_list;
        for (auto& [characteristic_uuid, characteristic] : service.characteristics) {
            // Build the list of descriptors for the characteristic.
            SharedPtrVector<DescriptorBase> descriptor_list;
            for (auto& [descriptor_uuid, descriptor] : characteristic.descriptors) {
                descriptor_list.push_back(std::make_shared<DescriptorBase>(descriptor_uuid));
            }

            uint32_t properties = MtaManager::get().execute_sync<uint32_t>([&characteristic]() {
                return (uint32_t)characteristic.obj.CharacteristicProperties();
            });

            bool can_read = (properties & (uint32_t)GattCharacteristicProperties::Read) != 0;
            bool can_write_request = (properties & (uint32_t)GattCharacteristicProperties::Write) != 0;
            bool can_write_command = (properties & (uint32_t)GattCharacteristicProperties::WriteWithoutResponse) != 0;
            bool can_notify = (properties & (uint32_t)GattCharacteristicProperties::Notify) != 0;
            bool can_indicate = (properties & (uint32_t)GattCharacteristicProperties::Indicate) != 0;

            characteristic_list.push_back(
                std::make_shared<CharacteristicBase>(characteristic_uuid, descriptor_list, can_read, can_write_request,
                                                     can_write_command, can_notify, can_indicate));
        }
        service_list.push_back(std::make_shared<ServiceBase>(service_uuid, characteristic_list));
    }

    return service_list;
}

SharedPtrVector<ServiceBase> PeripheralWindows::advertised_services() {
    SharedPtrVector<ServiceBase> service_list;
    for (auto& [service_uuid, data] : service_data_) {
        service_list.push_back(std::make_shared<ServiceBase>(service_uuid, data));
    }

    return service_list;
}

std::map<uint16_t, ByteArray> PeripheralWindows::manufacturer_data() { return manufacturer_data_; }

ByteArray PeripheralWindows::read(BluetoothUUID const& service, BluetoothUUID const& characteristic) {
    GattCharacteristic gatt_characteristic = _fetch_characteristic(service, characteristic).obj;

    return MtaManager::get().execute_sync<ByteArray>([this, &gatt_characteristic]() {
        // Validate that the operation can be performed.
        uint32_t gatt_characteristic_prop = (uint32_t)gatt_characteristic.CharacteristicProperties();
        if ((gatt_characteristic_prop & (uint32_t)GattCharacteristicProperties::Read) == 0) {
            throw SimpleBLE::Exception::OperationNotSupported("read", guid_to_uuid(gatt_characteristic.Uuid()));
        }

        // Read the value.
        auto result = async_get(gatt_characteristic.ReadValueAsync(Devices::Bluetooth::BluetoothCacheMode::Uncached));
        if (result.Status() != GenericAttributeProfile::GattCommunicationStatus::Success) {
            throw SimpleBLE::Exception::OperationFailed();
        }
        return ibuffer_to_bytearray(result.Value());
    });
}

void PeripheralWindows::write_request(BluetoothUUID const& service, BluetoothUUID const& characteristic,
                                      ByteArray const& data) {
    GattCharacteristic gatt_characteristic = _fetch_characteristic(service, characteristic).obj;

    MtaManager::get().execute_sync([this, &gatt_characteristic, &data]() {
        // Validate that the operation can be performed.
        uint32_t gatt_characteristic_prop = (uint32_t)gatt_characteristic.CharacteristicProperties();
        if ((gatt_characteristic_prop & (uint32_t)GattCharacteristicProperties::Write) == 0) {
            throw SimpleBLE::Exception::OperationNotSupported("write_request", guid_to_uuid(gatt_characteristic.Uuid()));
        }

        // Convert the request data to a buffer.
        winrt::Windows::Storage::Streams::IBuffer buffer = bytearray_to_ibuffer(data);

        // Write the value.
        auto result = async_get(gatt_characteristic.WriteValueAsync(buffer, GattWriteOption::WriteWithResponse));
        if (result != GenericAttributeProfile::GattCommunicationStatus::Success) {
            throw SimpleBLE::Exception::OperationFailed();
        }
    });
}

void PeripheralWindows::write_command(BluetoothUUID const& service, BluetoothUUID const& characteristic,
                                      ByteArray const& data) {
    GattCharacteristic gatt_characteristic = _fetch_characteristic(service, characteristic).obj;

    MtaManager::get().execute_sync([this, &gatt_characteristic, &data]() {
        // Validate that the operation can be performed.
        uint32_t gatt_characteristic_prop = (uint32_t)gatt_characteristic.CharacteristicProperties();
        if ((gatt_characteristic_prop & (uint32_t)GattCharacteristicProperties::WriteWithoutResponse) == 0) {
            throw SimpleBLE::Exception::OperationNotSupported("write_command", guid_to_uuid(gatt_characteristic.Uuid()));
        }

        // Convert the request data to a buffer.
        winrt::Windows::Storage::Streams::IBuffer buffer = bytearray_to_ibuffer(data);

        // Write the value.
        auto result = async_get(gatt_characteristic.WriteValueAsync(buffer, GattWriteOption::WriteWithoutResponse));
        if (result != GenericAttributeProfile::GattCommunicationStatus::Success) {
            throw SimpleBLE::Exception::OperationFailed();
        }
    });
}

void PeripheralWindows::notify(BluetoothUUID const& service, BluetoothUUID const& characteristic,
                               std::function<void(ByteArray payload)> callback) {
    _subscribe(service, characteristic, std::move(callback), GattCharacteristicProperties::Notify,
               GattClientCharacteristicConfigurationDescriptorValue::Notify);
}

void PeripheralWindows::indicate(BluetoothUUID const& service, BluetoothUUID const& characteristic,
                                 std::function<void(ByteArray payload)> callback) {
    _subscribe(service, characteristic, std::move(callback), GattCharacteristicProperties::Indicate,
               GattClientCharacteristicConfigurationDescriptorValue::Indicate);
}

void PeripheralWindows::unsubscribe(BluetoothUUID const& service, BluetoothUUID const& characteristic) {
    gatt_characteristic_t& gatt_characteristic_holder = _fetch_characteristic(service, characteristic);
    GattCharacteristic gatt_characteristic = gatt_characteristic_holder.obj;

    MtaManager::get().execute_sync([this, &gatt_characteristic, &gatt_characteristic_holder]() {
        if (gatt_characteristic_holder.value_changed_token) {
            // Unregister the callback.
            gatt_characteristic.ValueChanged(gatt_characteristic_holder.value_changed_token);
            gatt_characteristic_holder.value_changed_token = {0};
            gatt_characteristic_holder.value_changed_callback = nullptr;
        }

        // Start the indication.
        auto result = async_get(gatt_characteristic.WriteClientCharacteristicConfigurationDescriptorWithResultAsync(
            GattClientCharacteristicConfigurationDescriptorValue::None));

        if (result.Status() != GenericAttributeProfile::GattCommunicationStatus::Success) {
            throw SimpleBLE::Exception::OperationFailed();
        }
    });
}

ByteArray PeripheralWindows::read(BluetoothUUID const& service, BluetoothUUID const& characteristic,
                                  BluetoothUUID const& descriptor) {
    GattDescriptor gatt_descriptor = _fetch_descriptor(service, characteristic, descriptor);

    return MtaManager::get().execute_sync<ByteArray>([this, &gatt_descriptor]() {
        // Read the value.
        auto result = async_get(gatt_descriptor.ReadValueAsync(Devices::Bluetooth::BluetoothCacheMode::Uncached));
        if (result.Status() != GenericAttributeProfile::GattCommunicationStatus::Success) {
            throw SimpleBLE::Exception::OperationFailed();
        }
        return ibuffer_to_bytearray(result.Value());
    });
}

void PeripheralWindows::write(BluetoothUUID const& service, BluetoothUUID const& characteristic,
                              BluetoothUUID const& descriptor, ByteArray const& data) {
    GattDescriptor gatt_descriptor = _fetch_descriptor(service, characteristic, descriptor);

    MtaManager::get().execute_sync([this, &gatt_descriptor, &data]() {
        // Convert the request data to a buffer.
        winrt::Windows::Storage::Streams::IBuffer buffer = bytearray_to_ibuffer(data);

        // Write the value.
        auto result = async_get(gatt_descriptor.WriteValueWithResultAsync(buffer));
        if (result.Status() != GenericAttributeProfile::GattCommunicationStatus::Success) {
            throw SimpleBLE::Exception::OperationFailed();
        }
    });
}

void PeripheralWindows::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 PeripheralWindows::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 PeripheralWindows::_subscribe(BluetoothUUID const& service, BluetoothUUID const& characteristic,
                                   std::function<void(ByteArray payload)> callback,
                                   GattCharacteristicProperties property,
                                   GattClientCharacteristicConfigurationDescriptorValue descriptor_value) {
    gatt_characteristic_t& gatt_characteristic_holder = _fetch_characteristic(service, characteristic);
    GattCharacteristic gatt_characteristic = gatt_characteristic_holder.obj;

    MtaManager::get().execute_sync([this, &gatt_characteristic, &gatt_characteristic_holder, callback, property, descriptor_value]() {
        // Validate that the operation can be performed.
        uint32_t gatt_characteristic_prop = (uint32_t)gatt_characteristic.CharacteristicProperties();
        if ((gatt_characteristic_prop & (uint32_t)property) == 0) {
            std::string operation = (property == GattCharacteristicProperties::Notify) ? "notify" : "indicate";
            throw SimpleBLE::Exception::OperationNotSupported(operation, guid_to_uuid(gatt_characteristic.Uuid()));
        }

        // If a notification for the given characteristic is already in progress, swap the callbacks.
        if (gatt_characteristic_holder.value_changed_token) {
            SIMPLEBLE_LOG_WARN("A notification for the given characteristic is already in progress. Swapping callbacks.");
            // Unregister the callback.
            gatt_characteristic.ValueChanged(gatt_characteristic_holder.value_changed_token);
            gatt_characteristic_holder.value_changed_token = {0};
        }

        gatt_characteristic_holder.value_changed_callback = [=](const GattCharacteristic& sender,
                                                                const GattValueChangedEventArgs& args) {
            // Convert the payload to a ByteArray.
            ByteArray payload = ibuffer_to_bytearray(args.CharacteristicValue());
            SAFE_CALLBACK_CALL(callback, payload);
        };

        // Register the callback.
        gatt_characteristic_holder.value_changed_token = gatt_characteristic.ValueChanged(
            gatt_characteristic_holder.value_changed_callback);

        // Start the notification.
        auto result = async_get(
            gatt_characteristic.WriteClientCharacteristicConfigurationDescriptorWithResultAsync(descriptor_value));

        if (result.Status() != GenericAttributeProfile::GattCommunicationStatus::Success) {
            throw SimpleBLE::Exception::OperationFailed();
        }
    });
}

bool PeripheralWindows::_attempt_connect() {
    gatt_map_.clear();

    return MtaManager::get().execute_sync<bool>([this]() {
        // We need to cache all services, characteristics and descriptors in the class, else
        // the underlying objects will be garbage collected.
        auto services_result = async_get(device_.GetGattServicesAsync(BluetoothCacheMode::Uncached));
        if (services_result.Status() != GattCommunicationStatus::Success) {
            return false;
        }

        auto gatt_services = services_result.Services();
        for (GattDeviceService&& service : gatt_services) {
            // For each service...
            gatt_service_t gatt_service;
            gatt_service.obj = service;

            // Save the MTU size
            mtu_ = service.Session().MaxPduSize();

            // Fetch the service UUID
            std::string service_uuid = guid_to_uuid(service.Uuid());

            // Fetch the service characteristics
            GattCharacteristicsResult characteristics_result{nullptr};
            try {
                characteristics_result = async_get(service.GetCharacteristicsAsync(BluetoothCacheMode::Uncached));
            } catch (const SimpleBLE::Exception::WinRTAccessDenied&) {
                SIMPLEBLE_LOG_WARN(fmt::format("Access denied while discovering GATT service {}. Skipping service.",
                                               service_uuid));
                continue;
            }

            if (characteristics_result.Status() == GattCommunicationStatus::AccessDenied) {
                SIMPLEBLE_LOG_WARN(fmt::format("Access denied while discovering GATT service {}. Skipping service.",
                                               service_uuid));
                continue;
            } else if (characteristics_result.Status() != GattCommunicationStatus::Success) {
                return false;
            }

            // Load the characteristics into the service
            auto gatt_characteristics = characteristics_result.Characteristics();
            for (GattCharacteristic&& characteristic : gatt_characteristics) {
                // For each characteristic...
                gatt_characteristic_t gatt_characteristic;
                gatt_characteristic.obj = characteristic;

                // Fetch the characteristic UUID
                std::string characteristic_uuid = guid_to_uuid(characteristic.Uuid());

                // Fetch the characteristic descriptors
                auto descriptors_result = async_get(characteristic.GetDescriptorsAsync(BluetoothCacheMode::Uncached));
                if (descriptors_result.Status() != GattCommunicationStatus::Success) {
                    return false;
                }

                // Load the descriptors into the characteristic
                auto gatt_descriptors = descriptors_result.Descriptors();
                for (GattDescriptor&& descriptor : gatt_descriptors) {
                    // For each descriptor...
                    gatt_descriptor_t gatt_descriptor;
                    gatt_descriptor.obj = descriptor;

                    // Fetch the descriptor UUID.
                    std::string descriptor_uuid = guid_to_uuid(descriptor.Uuid());

                    // Append the descriptor to the characteristic.
                    gatt_characteristic.descriptors.emplace(descriptor_uuid, std::move(gatt_descriptor));
                }

                // Append the characteristic to the service.
                gatt_service.characteristics.emplace(characteristic_uuid, std::move(gatt_characteristic));
            }

            // Append the service to the map.
            gatt_map_.emplace(service_uuid, std::move(gatt_service));
        }

        return true;
    });
}

gatt_characteristic_t& PeripheralWindows::_fetch_characteristic(const BluetoothUUID& service_uuid,
                                                                const BluetoothUUID& characteristic_uuid) {
    if (gatt_map_.count(service_uuid) == 0) {
        throw SimpleBLE::Exception::ServiceNotFound(service_uuid);
    }

    if (gatt_map_[service_uuid].characteristics.count(characteristic_uuid) == 0) {
        throw SimpleBLE::Exception::CharacteristicNotFound(characteristic_uuid);
    }

    return gatt_map_[service_uuid].characteristics.at(characteristic_uuid);
}

GattDescriptor PeripheralWindows::_fetch_descriptor(const BluetoothUUID& service_uuid,
                                                    const BluetoothUUID& characteristic_uuid,
                                                    const BluetoothUUID& descriptor_uuid) {
    if (gatt_map_.count(service_uuid) == 0) {
        throw SimpleBLE::Exception::ServiceNotFound(service_uuid);
    }

    if (gatt_map_[service_uuid].characteristics.count(characteristic_uuid) == 0) {
        throw SimpleBLE::Exception::CharacteristicNotFound(characteristic_uuid);
    }

    if (gatt_map_[service_uuid].characteristics[characteristic_uuid].descriptors.count(descriptor_uuid) == 0) {
        throw SimpleBLE::Exception::DescriptorNotFound(descriptor_uuid);
    }

    return gatt_map_[service_uuid].characteristics[characteristic_uuid].descriptors.at(descriptor_uuid).obj;
}