forked from noble/noble
-
Notifications
You must be signed in to change notification settings - Fork 160
/
ble_manager.cc
805 lines (754 loc) · 27.3 KB
/
ble_manager.cc
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
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
//
// ble_manager.cc
// noble-winrt-native
//
// Created by Georg Vienna on 03.09.18.
//
#include "ble_manager.h"
#include "winrt_cpp.h"
#include <winrt/Windows.Foundation.Collections.h>
#include <winrt/Windows.Storage.Streams.h>
using winrt::Windows::Devices::Bluetooth::BluetoothCacheMode;
using winrt::Windows::Devices::Bluetooth::BluetoothConnectionStatus;
using winrt::Windows::Devices::Bluetooth::BluetoothLEDevice;
using winrt::Windows::Storage::Streams::DataReader;
using winrt::Windows::Storage::Streams::DataWriter;
using winrt::Windows::Storage::Streams::IBuffer;
template <typename T> auto inFilter(std::vector<T> filter, T object)
{
return filter.empty() || std::find(filter.begin(), filter.end(), object) != filter.end();
}
template <typename O, typename M, class... Types> auto bind2(O* object, M method, Types&... args)
{
return std::bind(method, object, std::placeholders::_1, std::placeholders::_2, args...);
}
#define LOGE(message, ...) printf(__FUNCTION__ ": " message "\n", __VA_ARGS__)
#define CHECK_DEVICE() \
if (mDeviceMap.find(uuid) == mDeviceMap.end()) \
{ \
LOGE("device with id %s not found", uuid.c_str()); \
return false; \
}
#define IFDEVICE(_device, _uuid) \
PeripheralWinrt& peripheral = mDeviceMap[_uuid]; \
if (!peripheral.device.has_value()) \
{ \
LOGE("device not connected"); \
return false; \
} \
BluetoothLEDevice& _device = *peripheral.device;
#define CHECK_RESULT(_result) \
if (!_result) \
{ \
LOGE("result is null"); \
return; \
} \
auto _commStatus = _result.Status(); \
if (_commStatus != GattCommunicationStatus::Success) \
{ \
LOGE("communication status: %d", _commStatus); \
return; \
}
#define FOR(object, vector) \
auto _vector = vector; \
if (!_vector) \
{ \
LOGE(#vector " is null"); \
return; \
} \
else \
for (auto&& object : _vector)
BLEManager::BLEManager(const Napi::Value& receiver, const Napi::Function& callback)
{
mRadioState = AdapterState::Initial;
mEmit.Wrap(receiver, callback);
auto onRadio = std::bind(&BLEManager::OnRadio, this, std::placeholders::_1);
mWatcher.Start(onRadio);
mAdvertismentWatcher.ScanningMode(BluetoothLEScanningMode::Active);
auto onReceived = bind2(this, &BLEManager::OnScanResult);
mReceivedRevoker = mAdvertismentWatcher.Received(winrt::auto_revoke, onReceived);
auto onStopped = bind2(this, &BLEManager::OnScanStopped);
mStoppedRevoker = mAdvertismentWatcher.Stopped(winrt::auto_revoke, onStopped);
}
const char* adapterStateToString(AdapterState state)
{
switch (state)
{
case AdapterState::Unsupported:
return "unsupported";
case AdapterState::On:
return "poweredOn";
break;
case AdapterState::Off:
return "poweredOff";
break;
case AdapterState::Disabled:
return "poweredOff";
break;
default:
return "unknown";
}
}
void BLEManager::OnRadio(Radio& radio)
{
auto state = AdapterState::Unsupported;
if (radio)
{
state = (AdapterState)radio.State();
}
if (state != mRadioState)
{
mRadioState = state;
mEmit.RadioState(adapterStateToString(state));
}
}
void BLEManager::Scan(const std::vector<winrt::guid>& serviceUUIDs, bool allowDuplicates)
{
mAdvertismentMap.clear();
mAllowDuplicates = allowDuplicates;
BluetoothLEAdvertisementFilter filter = BluetoothLEAdvertisementFilter();
BluetoothLEAdvertisement advertisment = BluetoothLEAdvertisement();
auto services = advertisment.ServiceUuids();
for (auto uuid : serviceUUIDs)
{
services.Append(uuid);
}
filter.Advertisement(advertisment);
mAdvertismentWatcher.AdvertisementFilter(filter);
mAdvertismentWatcher.Start();
mEmit.ScanState(true);
}
void BLEManager::OnScanResult(BluetoothLEAdvertisementWatcher watcher,
const BluetoothLEAdvertisementReceivedEventArgs& args)
{
uint64_t bluetoothAddress = args.BluetoothAddress();
std::string uuid = formatBluetoothUuid(bluetoothAddress);
int16_t rssi = args.RawSignalStrengthInDBm();
auto advertismentType = args.AdvertisementType();
if (mDeviceMap.find(uuid) == mDeviceMap.end())
{
mAdvertismentMap.insert(uuid);
auto peripheral =
PeripheralWinrt(bluetoothAddress, advertismentType, rssi, args.Advertisement());
mEmit.Scan(uuid, rssi, peripheral);
mDeviceMap.emplace(std::make_pair(uuid, std::move(peripheral)));
}
else
{
PeripheralWinrt& peripheral = mDeviceMap[uuid];
peripheral.Update(rssi, args.Advertisement(), advertismentType);
if (mAllowDuplicates || mAdvertismentMap.find(uuid) == mAdvertismentMap.end())
{
mAdvertismentMap.insert(uuid);
mEmit.Scan(uuid, rssi, peripheral);
}
}
}
void BLEManager::StopScan()
{
mAdvertismentWatcher.Stop();
}
void BLEManager::OnScanStopped(BluetoothLEAdvertisementWatcher watcher,
const BluetoothLEAdvertisementWatcherStoppedEventArgs& args)
{
mEmit.ScanState(false);
}
bool BLEManager::Connect(const std::string& uuid)
{
if (mDeviceMap.find(uuid) == mDeviceMap.end())
{
mEmit.Connected(uuid, "device not found");
return false;
}
PeripheralWinrt& peripheral = mDeviceMap[uuid];
if (!peripheral.device.has_value())
{
auto completed = bind2(this, &BLEManager::OnConnected, uuid);
BluetoothLEDevice::FromBluetoothAddressAsync(peripheral.bluetoothAddress)
.Completed(completed);
}
else
{
mEmit.Connected(uuid);
}
return true;
}
void BLEManager::OnConnected(IAsyncOperation<BluetoothLEDevice> asyncOp, AsyncStatus status,
const std::string uuid)
{
if (status == AsyncStatus::Completed)
{
BluetoothLEDevice device = asyncOp.GetResults();
// device can be null if the connection failed
if (device)
{
auto onChanged = bind2(this, &BLEManager::OnConnectionStatusChanged);
auto token = device.ConnectionStatusChanged(onChanged);
auto uuid = formatBluetoothUuid(device.BluetoothAddress());
PeripheralWinrt& peripheral = mDeviceMap[uuid];
peripheral.device = device;
peripheral.connectionToken = token;
mEmit.Connected(uuid);
}
else
{
mEmit.Connected(uuid, "could not connect to device: result is null");
}
}
else
{
mEmit.Connected(uuid, "could not connect to device");
}
}
bool BLEManager::Disconnect(const std::string& uuid)
{
CHECK_DEVICE();
PeripheralWinrt& peripheral = mDeviceMap[uuid];
peripheral.Disconnect();
mNotifyMap.Remove(uuid);
mEmit.Disconnected(uuid);
return true;
}
void BLEManager::OnConnectionStatusChanged(BluetoothLEDevice device,
winrt::Windows::Foundation::IInspectable inspectable)
{
if (device.ConnectionStatus() == BluetoothConnectionStatus::Disconnected)
{
auto uuid = formatBluetoothUuid(device.BluetoothAddress());
if (mDeviceMap.find(uuid) == mDeviceMap.end())
{
LOGE("device with id %s not found", uuid.c_str());
return;
}
PeripheralWinrt& peripheral = mDeviceMap[uuid];
peripheral.Disconnect();
mNotifyMap.Remove(uuid);
mEmit.Disconnected(uuid);
}
}
bool BLEManager::UpdateRSSI(const std::string& uuid)
{
CHECK_DEVICE();
PeripheralWinrt& peripheral = mDeviceMap[uuid];
// no way to get the rssi while we are connected, return the last value of advertisement
mEmit.RSSI(uuid, peripheral.rssi);
return true;
}
bool BLEManager::DiscoverServices(const std::string& uuid,
const std::vector<winrt::guid>& serviceUUIDs)
{
CHECK_DEVICE();
IFDEVICE(device, uuid)
{
auto completed = bind2(this, &BLEManager::OnServicesDiscovered, uuid, serviceUUIDs);
device.GetGattServicesAsync(BluetoothCacheMode::Uncached).Completed(completed);
return true;
}
}
void BLEManager::OnServicesDiscovered(IAsyncOperation<GattDeviceServicesResult> asyncOp,
AsyncStatus status, const std::string uuid,
const std::vector<winrt::guid> serviceUUIDs)
{
if (status == AsyncStatus::Completed)
{
GattDeviceServicesResult result = asyncOp.GetResults();
CHECK_RESULT(result);
std::vector<std::string> serviceUuids;
FOR(service, result.Services())
{
auto id = service.Uuid();
if (inFilter(serviceUUIDs, id))
{
serviceUuids.push_back(toStr(id));
}
}
mEmit.ServicesDiscovered(uuid, serviceUuids);
}
else
{
LOGE("status: %d", status);
}
}
bool BLEManager::DiscoverIncludedServices(const std::string& uuid, const winrt::guid& serviceUuid,
const std::vector<winrt::guid>& serviceUUIDs)
{
CHECK_DEVICE();
IFDEVICE(device, uuid)
{
peripheral.GetService(serviceUuid, [=](std::optional<GattDeviceService> service) {
if (service)
{
std::string serviceId = toStr(serviceUuid);
service->GetIncludedServicesAsync(BluetoothCacheMode::Uncached)
.Completed(bind2(this, &BLEManager::OnIncludedServicesDiscovered, uuid,
serviceId, serviceUUIDs));
}
else
{
LOGE("GetService error");
}
});
return true;
}
}
void BLEManager::OnIncludedServicesDiscovered(IAsyncOperation<GattDeviceServicesResult> asyncOp,
AsyncStatus status, const std::string uuid,
const std::string serviceId,
const std::vector<winrt::guid> serviceUUIDs)
{
if (status == AsyncStatus::Completed)
{
auto result = asyncOp.GetResults();
CHECK_RESULT(result);
std::vector<std::string> servicesUuids;
FOR(service, result.Services())
{
auto id = service.Uuid();
if (inFilter(serviceUUIDs, id))
{
servicesUuids.push_back(toStr(id));
}
}
mEmit.IncludedServicesDiscovered(uuid, serviceId, servicesUuids);
}
else
{
LOGE("status: %d", status);
}
}
bool BLEManager::DiscoverCharacteristics(const std::string& uuid, const winrt::guid& serviceUuid,
const std::vector<winrt::guid>& characteristicUUIDs)
{
CHECK_DEVICE();
IFDEVICE(device, uuid)
{
peripheral.GetService(serviceUuid, [=](std::optional<GattDeviceService> service) {
if (service)
{
std::string serviceId = toStr(serviceUuid);
service->GetCharacteristicsAsync(BluetoothCacheMode::Uncached)
.Completed(bind2(this, &BLEManager::OnCharacteristicsDiscovered, uuid,
serviceId, characteristicUUIDs));
}
else
{
LOGE("GetService error");
}
});
return true;
}
}
void BLEManager::OnCharacteristicsDiscovered(IAsyncOperation<GattCharacteristicsResult> asyncOp,
AsyncStatus status, const std::string uuid,
const std::string serviceId,
const std::vector<winrt::guid> characteristicUUIDs)
{
if (status == AsyncStatus::Completed)
{
auto result = asyncOp.GetResults();
CHECK_RESULT(result);
std::vector<std::pair<std::string, std::vector<std::string>>> characteristicsUuids;
FOR(characteristic, result.Characteristics())
{
auto id = characteristic.Uuid();
if (inFilter(characteristicUUIDs, id))
{
auto props = characteristic.CharacteristicProperties();
characteristicsUuids.push_back({ toStr(id), toPropertyArray(props) });
}
}
mEmit.CharacteristicsDiscovered(uuid, serviceId, characteristicsUuids);
}
else
{
LOGE("status: %d", status);
}
}
bool BLEManager::Read(const std::string& uuid, const winrt::guid& serviceUuid,
const winrt::guid& characteristicUuid)
{
CHECK_DEVICE();
IFDEVICE(device, uuid)
{
peripheral.GetCharacteristic(
serviceUuid, characteristicUuid, [=](std::optional<GattCharacteristic> characteristic) {
if (characteristic)
{
std::string serviceId = toStr(serviceUuid);
std::string characteristicId = toStr(characteristicUuid);
characteristic->ReadValueAsync(BluetoothCacheMode::Uncached)
.Completed(
bind2(this, &BLEManager::OnRead, uuid, serviceId, characteristicId));
}
else
{
LOGE("GetCharacteristic error");
}
});
return true;
}
}
void BLEManager::OnRead(IAsyncOperation<GattReadResult> asyncOp, AsyncStatus status,
const std::string uuid, const std::string serviceId,
const std::string characteristicId)
{
if (status == AsyncStatus::Completed)
{
GattReadResult result = asyncOp.GetResults();
CHECK_RESULT(result);
auto value = result.Value();
if (value)
{
auto reader = DataReader::FromBuffer(value);
Data data(reader.UnconsumedBufferLength());
reader.ReadBytes(data);
mEmit.Read(uuid, serviceId, characteristicId, data, false);
}
else
{
LOGE("value is null");
}
}
else
{
LOGE("status: %d", status);
}
}
bool BLEManager::Write(const std::string& uuid, const winrt::guid& serviceUuid,
const winrt::guid& characteristicUuid, const Data& data,
bool withoutResponse)
{
CHECK_DEVICE();
IFDEVICE(device, uuid)
{
peripheral.GetCharacteristic(
serviceUuid, characteristicUuid, [=](std::optional<GattCharacteristic> characteristic) {
if (characteristic)
{
std::string serviceId = toStr(serviceUuid);
std::string characteristicId = toStr(characteristicUuid);
auto writer = DataWriter();
writer.WriteBytes(data);
auto value = writer.DetachBuffer();
GattWriteOption option = withoutResponse ? GattWriteOption::WriteWithoutResponse
: GattWriteOption::WriteWithResponse;
characteristic->WriteValueWithResultAsync(value, option)
.Completed(
bind2(this, &BLEManager::OnWrite, uuid, serviceId, characteristicId));
}
else
{
LOGE("GetCharacteristic error");
}
});
return true;
}
}
void BLEManager::OnWrite(IAsyncOperation<GattWriteResult> asyncOp, AsyncStatus status,
const std::string uuid, const std::string serviceId,
const std::string characteristicId)
{
if (status == AsyncStatus::Completed)
{
mEmit.Write(uuid, serviceId, characteristicId);
}
else
{
LOGE("status: %d", status);
}
}
GattClientCharacteristicConfigurationDescriptorValue
GetDescriptorValue(GattCharacteristicProperties properties)
{
if ((properties & GattCharacteristicProperties::Indicate) ==
GattCharacteristicProperties::Indicate)
{
return GattClientCharacteristicConfigurationDescriptorValue::Indicate;
}
else
{
return GattClientCharacteristicConfigurationDescriptorValue::Notify;
}
}
bool BLEManager::Notify(const std::string& uuid, const winrt::guid& serviceUuid,
const winrt::guid& characteristicUuid, bool on)
{
CHECK_DEVICE();
IFDEVICE(device, uuid)
{
auto onCharacteristic = [=](std::optional<GattCharacteristic> characteristic) {
if (characteristic)
{
std::string serviceId = toStr(serviceUuid);
std::string characteristicId = toStr(characteristicUuid);
bool subscribed = mNotifyMap.IsSubscribed(uuid, *characteristic);
if (on)
{
if (subscribed)
{
// already listening
mEmit.Notify(uuid, serviceId, characteristicId, true);
return;
}
auto descriptorValue =
GetDescriptorValue(characteristic->CharacteristicProperties());
auto completed = bind2(this, &BLEManager::OnNotify, *characteristic, uuid,
serviceId, characteristicId, on);
characteristic
->WriteClientCharacteristicConfigurationDescriptorWithResultAsync(
descriptorValue)
.Completed(completed);
}
else
{
if (!subscribed)
{
// already not listening
mEmit.Notify(uuid, serviceId, characteristicId, false);
return;
}
mNotifyMap.Unsubscribe(uuid, *characteristic);
auto descriptorValue =
GattClientCharacteristicConfigurationDescriptorValue::None;
auto completed = bind2(this, &BLEManager::OnNotify, *characteristic, uuid,
serviceId, characteristicId, on);
characteristic
->WriteClientCharacteristicConfigurationDescriptorWithResultAsync(
descriptorValue)
.Completed(completed);
}
}
else
{
LOGE("GetCharacteristic error");
}
};
peripheral.GetCharacteristic(serviceUuid, characteristicUuid, onCharacteristic);
return true;
}
}
void BLEManager::OnNotify(IAsyncOperation<GattWriteResult> asyncOp, AsyncStatus status,
const GattCharacteristic characteristic, const std::string uuid,
const std::string serviceId, const std::string characteristicId,
const bool state)
{
if (status == AsyncStatus::Completed)
{
if (state == true)
{
auto onChanged = bind2(this, &BLEManager::OnValueChanged, uuid);
auto token = characteristic.ValueChanged(onChanged);
mNotifyMap.Add(uuid, characteristic, token);
}
mEmit.Notify(uuid, serviceId, characteristicId, state);
}
else
{
LOGE("status: %d", status);
}
}
void BLEManager::OnValueChanged(GattCharacteristic characteristic,
const GattValueChangedEventArgs& args, std::string deviceUuid)
{
auto reader = DataReader::FromBuffer(args.CharacteristicValue());
Data data(reader.UnconsumedBufferLength());
reader.ReadBytes(data);
auto characteristicUuid = toStr(characteristic.Uuid());
auto serviceUuid = toStr(characteristic.Service().Uuid());
mEmit.Read(deviceUuid, serviceUuid, characteristicUuid, data, true);
}
bool BLEManager::DiscoverDescriptors(const std::string& uuid, const winrt::guid& serviceUuid,
const winrt::guid& characteristicUuid)
{
CHECK_DEVICE();
IFDEVICE(device, uuid)
{
peripheral.GetCharacteristic(
serviceUuid, characteristicUuid, [=](std::optional<GattCharacteristic> characteristic) {
if (characteristic)
{
std::string serviceId = toStr(serviceUuid);
std::string characteristicId = toStr(characteristicUuid);
auto completed = bind2(this, &BLEManager::OnDescriptorsDiscovered, uuid,
serviceId, characteristicId);
characteristic->GetDescriptorsAsync(BluetoothCacheMode::Uncached)
.Completed(completed);
}
else
{
LOGE("GetCharacteristic error");
}
});
return true;
}
}
void BLEManager::OnDescriptorsDiscovered(IAsyncOperation<GattDescriptorsResult> asyncOp,
AsyncStatus status, const std::string uuid,
const std::string serviceId,
const std::string characteristicId)
{
if (status == AsyncStatus::Completed)
{
auto result = asyncOp.GetResults();
CHECK_RESULT(result);
std::vector<std::string> descriptorUuids;
FOR(descriptor, result.Descriptors())
{
descriptorUuids.push_back(toStr(descriptor.Uuid()));
}
mEmit.DescriptorsDiscovered(uuid, serviceId, characteristicId, descriptorUuids);
}
else
{
LOGE("status: %d", status);
}
}
bool BLEManager::ReadValue(const std::string& uuid, const winrt::guid& serviceUuid,
const winrt::guid& characteristicUuid, const winrt::guid& descriptorUuid)
{
CHECK_DEVICE();
IFDEVICE(device, uuid)
{
peripheral.GetDescriptor(
serviceUuid, characteristicUuid, descriptorUuid,
[=](std::optional<GattDescriptor> descriptor) {
if (descriptor)
{
std::string serviceId = toStr(serviceUuid);
std::string characteristicId = toStr(characteristicUuid);
std::string descriptorId = toStr(descriptorUuid);
auto completed = bind2(this, &BLEManager::OnReadValue, uuid, serviceId,
characteristicId, descriptorId);
descriptor->ReadValueAsync(BluetoothCacheMode::Uncached).Completed(completed);
}
else
{
LOGE("descriptor not found");
}
});
return true;
}
}
void BLEManager::OnReadValue(IAsyncOperation<GattReadResult> asyncOp, AsyncStatus status,
const std::string uuid, const std::string serviceId,
const std::string characteristicId, const std::string descriptorId)
{
if (status == AsyncStatus::Completed)
{
GattReadResult result = asyncOp.GetResults();
CHECK_RESULT(result);
auto value = result.Value();
if (value)
{
auto reader = DataReader::FromBuffer(value);
Data data(reader.UnconsumedBufferLength());
reader.ReadBytes(data);
mEmit.ReadValue(uuid, serviceId, characteristicId, descriptorId, data);
}
else
{
LOGE("value is null");
}
}
else
{
LOGE("status: %d", status);
}
}
bool BLEManager::WriteValue(const std::string& uuid, const winrt::guid& serviceUuid,
const winrt::guid& characteristicUuid,
const winrt::guid& descriptorUuid, const Data& data)
{
CHECK_DEVICE();
IFDEVICE(device, uuid)
{
auto onDescriptor = [=](std::optional<GattDescriptor> descriptor) {
if (descriptor)
{
std::string serviceId = toStr(serviceUuid);
std::string characteristicId = toStr(characteristicUuid);
std::string descriptorId = toStr(descriptorUuid);
auto writer = DataWriter();
writer.WriteBytes(data);
auto value = writer.DetachBuffer();
auto asyncOp = descriptor->WriteValueWithResultAsync(value);
asyncOp.Completed(bind2(this, &BLEManager::OnWriteValue, uuid, serviceId,
characteristicId, descriptorId));
}
else
{
LOGE("descriptor not found");
}
};
peripheral.GetDescriptor(serviceUuid, characteristicUuid, descriptorUuid, onDescriptor);
return true;
}
}
void BLEManager::OnWriteValue(IAsyncOperation<GattWriteResult> asyncOp, AsyncStatus status,
const std::string uuid, const std::string serviceId,
const std::string characteristicId, const std::string descriptorId)
{
if (status == AsyncStatus::Completed)
{
mEmit.WriteValue(uuid, serviceId, characteristicId, descriptorId);
}
else
{
LOGE("status: %d", status);
}
}
bool BLEManager::ReadHandle(const std::string& uuid, int handle)
{
CHECK_DEVICE();
IFDEVICE(device, uuid)
{
LOGE("not available");
return true;
}
}
void BLEManager::OnReadHandle(IAsyncOperation<GattReadResult> asyncOp, AsyncStatus status,
const std::string uuid, const int handle)
{
if (status == AsyncStatus::Completed)
{
GattReadResult result = asyncOp.GetResults();
CHECK_RESULT(result);
auto value = result.Value();
if (value)
{
auto reader = DataReader::FromBuffer(value);
Data data(reader.UnconsumedBufferLength());
reader.ReadBytes(data);
mEmit.ReadHandle(uuid, handle, data);
}
else
{
LOGE("value is null");
}
}
else
{
LOGE("status: %d", status);
}
}
bool BLEManager::WriteHandle(const std::string& uuid, int handle, Data data)
{
CHECK_DEVICE();
IFDEVICE(device, uuid)
{
LOGE("not available");
return true;
}
}
void BLEManager::OnWriteHandle(IAsyncOperation<GattWriteResult> asyncOp, AsyncStatus status,
const std::string uuid, const int handle)
{
if (status == AsyncStatus::Completed)
{
mEmit.WriteHandle(uuid, handle);
}
else
{
LOGE("status %d", status);
}
}