-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathDiceBLEWin.cpp
More file actions
1488 lines (1336 loc) · 50 KB
/
Copy pathDiceBLEWin.cpp
File metadata and controls
1488 lines (1336 loc) · 50 KB
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
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#include "stdafx.h"
#include "DiceBLEWin.h"
#include "Utils.h"
#pragma warning (disable: 4068)
#include <windows.h>
#include <stdio.h>
#include <tchar.h>
#include <setupapi.h>
#include <devguid.h>
#include <regstr.h>
#include <bthdef.h>
#include <bluetoothleapis.h>
#include <comdef.h>
#include <iostream>
#include <sstream>
#include <string>
#include <locale>
#include <array>
#include <vector>
#include <algorithm> // std::find_if
#include <regex>
#include <mutex> // std::mutex, std::unique_lock, std::defer_lock
#include <thread> // std::this_thread::get_id
#include <ctime> // std::gmtime
#include <chrono> // std::system_clock
#pragma comment(lib, "SetupAPI")
#pragma comment(lib, "BluetoothApis.lib")
//#define LOG_TO_FILE
void LogToFile(const char* message)
{
#if defined(LOG_TO_FILE)
char buf[256];
sprintf_s(buf, 256, "%08x:%s", GetCurrentThreadId(), message);
FILE* f = NULL;
fopen_s(&f, "c:\\temp\\debuglog.txt", "a+");
while (f == NULL) {
Sleep(10);
fopen_s(&f, "c:\\temp\\debuglog.txt", "a+");
}
fprintf(f, buf);
fprintf(f, "\n");
fclose(f);
#endif
}
inline void LogToFile(const std::string& message)
{
LogToFile(message.data());
}
static DebugCallback debugLogCallback = nullptr;
static DebugCallback debugWarningCallback = nullptr;
static DebugCallback debugErrorCallback = nullptr;
static SendBluetoothMessageCallback sendMessageCallback = nullptr;
struct BLEDeviceInfo
{
GUID containerId;
std::string deviceName;
};
struct BLEServiceInfo
{
GUID containerId; // Used to match service and devices...
BTH_LE_UUID id;
std::string name;
std::string path;
BLEDeviceInfo* device;
};
struct BLEConnectedServiceInfo
{
HANDLE deviceHandle;
BTH_LE_GATT_SERVICE gattService;
BLEServiceInfo* service;
std::vector<BTH_LE_GATT_CHARACTERISTIC> characteristics;
};
struct BLERegisteredCharacteristicInfo
{
BLEConnectedServiceInfo* service;
BTH_LE_GATT_CHARACTERISTIC characteristic;
BLUETOOTH_GATT_EVENT_HANDLE characteristicHandle;
};
std::vector<BLEDeviceInfo*> devices;
std::vector<BLEServiceInfo*> services;
std::vector<BLEConnectedServiceInfo*> connectedServices;
std::vector<BLERegisteredCharacteristicInfo*> registeredCharacteristics;
enum class QueuedMessageType
{
Message = 0,
Log,
Warning,
Error,
};
struct QueuedMessage
{
QueuedMessage(const QueuedMessageType& messageType, const std::string& message)
: _messageType{ messageType }
, _message{ message }
, _threadId{ GetCurrentThreadId() }
, _timestamp{ std::chrono::duration_cast<std::chrono::microseconds>(
std::chrono::system_clock::now().time_since_epoch()
).count() }
{}
QueuedMessageType messageType() const { return _messageType; }
const std::string& message() const { return _message; }
thread_id_t threadId() const { return _threadId; }
timestamp_us_t timestamp() const { return _timestamp; }
private:
QueuedMessageType _messageType;
std::string _message;
thread_id_t _threadId;
timestamp_us_t _timestamp;
};
std::vector<QueuedMessage> messages;
std::mutex messageMutex; // mutex for critical section
// --------------------------------------------------------------------------
// Talks back to the mono side of things!
// --------------------------------------------------------------------------
inline void SendBluetoothMessage(const std::string& message)
{
const std::lock_guard<std::mutex> lock{ messageMutex };
messages.push_back({ QueuedMessageType::Message, message });
}
// --------------------------------------------------------------------------
// Sends a log to the mono side of things
// --------------------------------------------------------------------------
inline void DebugLog(const std::string& message)
{
const std::lock_guard<std::mutex> lock{ messageMutex };
messages.push_back({ QueuedMessageType::Log, message });
}
// --------------------------------------------------------------------------
// Sends a log to the mono side of things
// --------------------------------------------------------------------------
inline void DebugWarning(const std::string& message)
{
const std::lock_guard<std::mutex> lock{ messageMutex };
messages.push_back({ QueuedMessageType::Warning, message });
}
// --------------------------------------------------------------------------
// Sends a log to the mono side of things
// --------------------------------------------------------------------------
inline void DebugError(const std::string& message)
{
const std::lock_guard<std::mutex> lock{ messageMutex };
messages.push_back({ QueuedMessageType::Error, message });
}
// --------------------------------------------------------------------------
// Sends a bluetooth error message
// --------------------------------------------------------------------------
void SendError(const char* message)
{
std::string errorMessage = "Error~";
errorMessage.append(message);
SendBluetoothMessage(errorMessage);
DebugError(message);
}
inline void SendError(const std::string& message)
{
SendError(message.data());
}
// --------------------------------------------------------------------------
// Sends a BLT out of memory error message
// --------------------------------------------------------------------------
void SendOutOfMemoryError(int size)
{
SendError(std::string("Failed to allocate ").append(std::to_string(size)).append(" bytes of memory."));
}
// --------------------------------------------------------------------------
// Called by mono side to hook up message handlers!
// --------------------------------------------------------------------------
void _winBluetoothLEConnectCallbacks(SendBluetoothMessageCallback sendMessageMethod, DebugCallback logMethod, DebugCallback warningMethod, DebugCallback errorMethod)
{
sendMessageCallback = sendMessageMethod;
debugLogCallback = logMethod;
debugWarningCallback = warningMethod;
debugErrorCallback = errorMethod;
DebugLog("Hooked Debug Functions");
}
void _winBluetoothLEDisconnectCallbacks()
{
sendMessageCallback = nullptr;
debugLogCallback = nullptr;
debugWarningCallback = nullptr;
debugErrorCallback = nullptr;
}
// --------------------------------------------------------------------------
// Reads a device Property, used to retrieve device name, address, etc...
// --------------------------------------------------------------------------
std::string ReadProperty(HDEVINFO hDevInfo, PSP_DEVINFO_DATA pDeviceInfoData, DWORD property)
{
//DebugLog(std::string("ReadProperty: ").append(BLEUtils::GUIDToString(pDeviceInfoData->ClassGuid)).append(", ").append(std::to_string(property)));
DWORD regDataType;
LPTSTR buffer = nullptr;
DWORD buffersSize = 0;
while (!SetupDiGetDeviceRegistryProperty(hDevInfo, pDeviceInfoData, property, ®DataType, (PBYTE)buffer, buffersSize, &buffersSize))
{
if (GetLastError() == ERROR_INSUFFICIENT_BUFFER)
{
// Change the buffer size.
delete[] buffer;
// Double the size to avoid problems on
// W2k MBCS systems per KB 888609.
buffer = new wchar_t[buffersSize * 2];
}
else
{
wchar_t buf[256];
FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, NULL, GetLastError(), MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), buf, 256, NULL);
SendError(std::string("Could not read device property: ").append(BLEUtils::ToNarrow(buf)));
break;
}
}
std::string prop = "";
if (buffer != nullptr)
{
prop = BLEUtils::ToNarrow(buffer);
delete[] buffer;
}
return prop;
}
// --------------------------------------------------------------------------
// Reads a device's instance Id, used to generate the device path and later open handle to it
// --------------------------------------------------------------------------
std::string ReadDeviceInstanceId(HDEVINFO hDevInfo, PSP_DEVINFO_DATA pDeviceInfoData)
{
//DebugLog(std::string("ReadDeviceInstanceId: ").append(BLEUtils::GUIDToString(pDeviceInfoData->ClassGuid)));
LPTSTR deviceIdBuffer = nullptr;
DWORD deviceIdBufferSize = 0;
while (!SetupDiGetDeviceInstanceId(hDevInfo, pDeviceInfoData, deviceIdBuffer, deviceIdBufferSize, &deviceIdBufferSize))
{
if (GetLastError() == ERROR_INSUFFICIENT_BUFFER)
{
delete[] deviceIdBuffer;
deviceIdBuffer = new wchar_t[deviceIdBufferSize * 2];
}
else
{
wchar_t buf[256];
FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, NULL, GetLastError(), MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), buf, 256, NULL);
SendError(std::string("Could not read device instance Id: ").append(BLEUtils::ToNarrow(buf)));
break;
}
}
std::string id = "<no_id>";
if (deviceIdBuffer != nullptr)
{
id = BLEUtils::ToNarrow(deviceIdBuffer);
delete[] deviceIdBuffer;
}
return id;
}
// --------------------------------------------------------------------------
// Reads a device's interface details, we use this to get service GUIDs
// --------------------------------------------------------------------------
std::string ReadDeviceInterfaceDetails(HDEVINFO hDevInfo, PSP_DEVINFO_DATA pDeviceInfoData, PSP_DEVICE_INTERFACE_DATA pDeviceInterfaceData)
{
DebugLog(std::string("ReadDeviceInterfaceDetails: ").append(BLEUtils::GUIDToString(pDeviceInfoData->ClassGuid)));
PSP_DEVICE_INTERFACE_DETAIL_DATA pInterfaceDetailData = NULL;
DWORD size = 0;
while (!SetupDiGetDeviceInterfaceDetail(hDevInfo, pDeviceInterfaceData, NULL, size, &size, pDeviceInfoData))
{
if (GetLastError() == ERROR_INSUFFICIENT_BUFFER)
{
free(pInterfaceDetailData);
pInterfaceDetailData = (PSP_DEVICE_INTERFACE_DETAIL_DATA)malloc(size);
if (pInterfaceDetailData != nullptr)
{
RtlZeroMemory(pInterfaceDetailData, size);
pInterfaceDetailData->cbSize = sizeof(SP_DEVICE_INTERFACE_DETAIL_DATA);
}
else
{
SendOutOfMemoryError(size);
break;
}
}
else
{
free(pInterfaceDetailData);
pInterfaceDetailData = nullptr;
wchar_t buf[256];
FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, NULL, GetLastError(), MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), buf, 256, NULL);
SendError(std::string("Could not read device interface details: ").append(BLEUtils::ToNarrow(buf)));
break;
}
}
std::string ret = "<no path>";
if (pInterfaceDetailData != nullptr)
{
ret = BLEUtils::ToNarrow(pInterfaceDetailData->DevicePath);
free(pInterfaceDetailData);
}
return ret;
}
// --------------------------------------------------------------------------
// Finds all the bluetooth devices
// --------------------------------------------------------------------------
bool ScanBLEInterfaces()
{
DebugLog("ScanBLEInterfaces");
HDEVINFO hDevInfo;
SP_DEVINFO_DATA DeviceInfoData;
DWORD i;
// Create a HDEVINFO with all present devices.
hDevInfo = SetupDiGetClassDevs(&GUID_DEVCLASS_BLUETOOTH, 0, 0, DIGCF_PRESENT);
if (hDevInfo == INVALID_HANDLE_VALUE)
{
wchar_t buf[256];
FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, NULL, GetLastError(), MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), buf, 256, NULL);
SendError(std::string("Could not request bluetooth device list: ").append(BLEUtils::ToNarrow(buf)));
return false;
}
// Enumerate through all devices in Set.
DeviceInfoData.cbSize = sizeof(SP_DEVINFO_DATA);
for (i = 0; SetupDiEnumDeviceInfo(hDevInfo, i, &DeviceInfoData); i++)
{
// Check the hardware Id
std::string hardwareId = ReadProperty(hDevInfo, &DeviceInfoData, SPDRP_HARDWAREID);
// We're only interested in entries that start with either 'BTHLE\' or 'BTHLEDEVICE\'
bool isDevice = hardwareId.find("BTHLE\\") == 0;
bool isService = hardwareId.find("BTHLEDevice\\") == 0;
if (!isDevice && !isService)
{
continue;
}
// Then grab the container GUID, this is what we use to match devices and services to the same physical device
GUID containerGUID = BLEUtils::StringToGUID(ReadProperty(hDevInfo, &DeviceInfoData, SPDRP_BASE_CONTAINERID));
if (isDevice)
{
// Only add new devices
auto prev = std::find_if(devices.begin(), devices.end(), [&containerGUID](const BLEDeviceInfo* x) { return x->containerId == containerGUID; });
if (prev == devices.end())
{
// Fetch the name!
auto info = new BLEDeviceInfo();
info->deviceName = ReadProperty(hDevInfo, &DeviceInfoData, SPDRP_FRIENDLYNAME);
info->containerId = containerGUID;
devices.push_back(info);
}
}
if (isService)
{
// Fetch the GUID!
std::regex guidRegex("\\{.*\\}");
std::smatch match;
if (std::regex_search(hardwareId, match, guidRegex))
{
std::string guidString = match.str();
auto serviceId = BLEUtils::StringToBTHLEUUID(guidString);
auto prev = std::find_if(services.begin(), services.end(),
[&containerGUID, &serviceId](const BLEServiceInfo* x)
{
return x->containerId == containerGUID && x->id == serviceId;
});
if (prev == services.end())
{
auto service = new BLEServiceInfo();
service->name = ReadProperty(hDevInfo, &DeviceInfoData, SPDRP_DEVICEDESC);
service->containerId = containerGUID;
service->id = serviceId;
// Parse the device instance id to get the device path!
std::string deviceId = ReadDeviceInstanceId(hDevInfo, &DeviceInfoData);
// Create the device path
std::string path = "\\\\?\\";
std::replace(deviceId.begin(), deviceId.end(), '\\', '#');
path.append(deviceId);
path.append("#");
path.append(guidString);
service->path = path;
services.push_back(service);
}
}
else
{
SendError(std::string("Could not extract service GUID from the hardware ID \'").append(hardwareId).append("\'"));
}
}
}
// Set device pointers
for (auto service : services)
{
auto devIt = std::find_if(devices.begin(), devices.end(), [service](BLEDeviceInfo* d) { return d->containerId == service->containerId; });
if (devIt != devices.end())
{
service->device = *devIt;
}
else
{
SendError(std::string("Could not find the device that service ").append(BLEUtils::BTHLEGUIDToString(service->id)).append(" belongs to"));
}
}
SetupDiDestroyDeviceInfoList(hDevInfo);
return 0;
}
// --------------------------------------------------------------------------
// Iterates over all devices and sends notifications back for each one that matches the UUIDs passed in
// --------------------------------------------------------------------------
void notifyDevicesWithServices(const std::vector<BTH_LE_UUID>& uuids)
{
std::vector<GUID> returnedDevices;
// Find any device that has a service whose UUID matches one of the UUIDs passed in!
for (auto service : services)
{
auto prev = std::find_if(connectedServices.begin(), connectedServices.end(), [service](const BLEConnectedServiceInfo* x) { return x->service == service; });
if (prev == connectedServices.end())
{
// Not already connected, good!
if (std::find(uuids.begin(), uuids.end(), service->id) != uuids.end())
// Does this service match the UUID?
{
// Yes, send a message for each discovered peripheral
// Sadly we don't have access to advertisement data, it is managed by Windows!
std::string deviceDiscoveredMessage = "DiscoveredPeripheral~";
deviceDiscoveredMessage.append(BLEUtils::GUIDToString(service->device->containerId));
deviceDiscoveredMessage.append("~");
deviceDiscoveredMessage.append(service->device->deviceName);
SendBluetoothMessage(deviceDiscoveredMessage);
}
}
}
}
// --------------------------------------------------------------------------
// Iterates over all devices and sends notifications back for each one
// --------------------------------------------------------------------------
void notifyAllDevices()
{
// Find any device that has a service whose UUID matches one of the UUIDs passed in!
for (auto device : devices)
{
// Send a message for each discovered peripheral
// Sadly we don't have access to advertisement data...
std::string deviceDiscoveredMessage = "DiscoveredPeripheral~";
deviceDiscoveredMessage.append(BLEUtils::GUIDToString(device->containerId));
deviceDiscoveredMessage.append("~");
deviceDiscoveredMessage.append(device->deviceName);
SendBluetoothMessage(deviceDiscoveredMessage);
}
}
// --------------------------------------------------------------------------
// Iterates over all connected devices and sends notifications back for each one that matches the UUIDs passed in
// --------------------------------------------------------------------------
void notifyConnectedServices(const std::vector<BTH_LE_UUID>& uuids)
{
// Send messages for all the ones
for (auto service : connectedServices)
{
// Find any service that has a service whose UUID matches one of the UUIDs passed in!
if (std::find_if(uuids.begin(), uuids.end(), [&service](const BTH_LE_UUID& uuid) { return service->service->id == uuid; }) != uuids.end())
{
std::string deviceDiscoveredMessage = "RetrievedConnectedPeripheral~";
deviceDiscoveredMessage.append(BLEUtils::GUIDToString(service->service->device->containerId));
deviceDiscoveredMessage.append("~");
deviceDiscoveredMessage.append(service->service->device->deviceName);
SendBluetoothMessage(deviceDiscoveredMessage);
}
}
}
// --------------------------------------------------------------------------
// Iterates over all connected devices and sends notifications back for each one
// --------------------------------------------------------------------------
void notifyAllConnected()
{
// Send messages for all the ones
for (auto service : connectedServices)
{
// Send a message for each discovered service
std::string connectedDeviceRetrievedMessage = "RetrievedConnectedPeripheral~";
connectedDeviceRetrievedMessage.append(BLEUtils::GUIDToString(service->service->device->containerId));
connectedDeviceRetrievedMessage.append("~");
connectedDeviceRetrievedMessage.append(service->service->device->deviceName);
SendBluetoothMessage(connectedDeviceRetrievedMessage);
}
}
// --------------------------------------------------------------------------
// Retrieves the GATT service struct that matches the given service
// --------------------------------------------------------------------------
bool GetGATTService(HANDLE serviceHandle, BTH_LE_GATT_SERVICE& outService)
{
DebugLog("GetGATTService");
// Get GATT service
PBTH_LE_GATT_SERVICE services = nullptr;
USHORT serviceCount = 0;
HRESULT hr = S_OK;
while ((hr = BluetoothGATTGetServices(serviceHandle, serviceCount, services, &serviceCount, BLUETOOTH_GATT_FLAG_NONE)) != S_OK)
{
if (hr == HRESULT_FROM_WIN32(ERROR_MORE_DATA))
{
// Change the buffer size.
delete[] services;
services = new BTH_LE_GATT_SERVICE[serviceCount];
}
else
{
_com_error err(hr);
SendError(std::string("Could not retrieve service GATT info: ").append(BLEUtils::ToNarrow(err.ErrorMessage())));
break;
}
}
bool ret = hr == S_OK && serviceCount > 0 && services != nullptr;
if (ret)
{
// Only grab the first service!
outService = services[0];
}
delete[] services;
return ret;
}
// --------------------------------------------------------------------------
// Retrieves the characteristics associated with a service
// --------------------------------------------------------------------------
std::vector<BTH_LE_GATT_CHARACTERISTIC> GetGATTCharacteristics(HANDLE serviceHandle, BTH_LE_GATT_SERVICE& gattService)
{
DebugLog("GetGATTCharacteristics");
std::vector<BTH_LE_GATT_CHARACTERISTIC> ret;
PBTH_LE_GATT_CHARACTERISTIC characteristicsBuffer = nullptr;
USHORT characteristicCount = 0;
HRESULT hr = S_OK;
while ((hr = BluetoothGATTGetCharacteristics(serviceHandle, &gattService, characteristicCount, characteristicsBuffer, &characteristicCount, BLUETOOTH_GATT_FLAG_NONE)) != S_OK)
{
if (hr == HRESULT_FROM_WIN32(ERROR_MORE_DATA))
{
// Change the buffer size.
ret.resize(characteristicCount);
// And have the method write directly into the vector!
characteristicsBuffer = ret.data();
}
else
{
_com_error err(hr);
SendError(std::string("Could not retrieve service characteristics: ").append(BLEUtils::ToNarrow(err.ErrorMessage())));
break;
}
}
return ret;
}
// --------------------------------------------------------------------------
// Retrieves a characteristic's value, allocates memory because the data has variable size!
// --------------------------------------------------------------------------
PBTH_LE_GATT_CHARACTERISTIC_VALUE AllocAndReadCharacteristic(HANDLE serviceHandle, BTH_LE_GATT_CHARACTERISTIC* currGattChar)
{
DebugLog(std::string("AllocAndReadCharacteristic: ").append(BLEUtils::BTHLEGUIDToString(currGattChar->CharacteristicUuid)));
PBTH_LE_GATT_CHARACTERISTIC_VALUE pCharValueBuffer = nullptr;
if (currGattChar->IsReadable)
{
// Determine Characteristic Value Buffer Size
USHORT charValueDataSize = 0;
HRESULT hr = S_OK;
while ((hr = BluetoothGATTGetCharacteristicValue(serviceHandle, currGattChar, (ULONG)charValueDataSize, pCharValueBuffer, &charValueDataSize, BLUETOOTH_GATT_FLAG_NONE)) != S_OK)
{
if (hr == HRESULT_FROM_WIN32(ERROR_MORE_DATA))
{
free(pCharValueBuffer);
pCharValueBuffer = (PBTH_LE_GATT_CHARACTERISTIC_VALUE)malloc(charValueDataSize);
if (pCharValueBuffer != nullptr)
{
RtlZeroMemory(pCharValueBuffer, charValueDataSize);
pCharValueBuffer->DataSize = charValueDataSize;
}
else
{
SendOutOfMemoryError(charValueDataSize);
break;
}
}
else
{
free(pCharValueBuffer);
pCharValueBuffer = nullptr;
_com_error err(hr);
SendError(std::string("Could not get characteristic ").append(BLEUtils::BTHLEGUIDToString(currGattChar->CharacteristicUuid)).append(" value: ").append(BLEUtils::ToNarrow(err.ErrorMessage())));
}
}
}
else
{
SendError(std::string("Characteristic ").append(BLEUtils::BTHLEGUIDToString(currGattChar->CharacteristicUuid)).append(" is not readable."));
}
return pCharValueBuffer;
}
// --------------------------------------------------------------------------
// Disconnects ALL connected services associated with a device!
// --------------------------------------------------------------------------
bool DisconnectServicesForDevice(GUID addressGUID)
{
DebugLog(std::string("DisconnectServicesForDevice: ").append(BLEUtils::GUIDToString(addressGUID)));
bool disconnectedService = false;
for (auto servIt = connectedServices.begin(); servIt != connectedServices.end();)
{
auto cservice = *servIt;
if (cservice->service->device->containerId == addressGUID)
{
// Do we have any registered characteristics?
for (auto charIt = registeredCharacteristics.begin(); charIt != registeredCharacteristics.end();)
{
auto charInfo = *charIt;
if (charInfo->service->service->device->containerId == addressGUID)
{
// We should unregister!
HRESULT hr = BluetoothGATTUnregisterEvent(charInfo->characteristicHandle, BLUETOOTH_GATT_FLAG_NONE);
if (hr == S_OK)
{
// Send message
std::string registerCharacteristicMessage = "DidUpdateNotificationStateForCharacteristic~";
registerCharacteristicMessage.append(BLEUtils::GUIDToString(addressGUID));
registerCharacteristicMessage.append("~");
registerCharacteristicMessage.append(BLEUtils::BTHLEGUIDToString(cservice->service->id));
registerCharacteristicMessage.append("~");
registerCharacteristicMessage.append(BLEUtils::BTHLEGUIDToString(charInfo->characteristic.CharacteristicUuid));
SendBluetoothMessage(registerCharacteristicMessage);
// Clean up
delete charInfo;
charIt = registeredCharacteristics.erase(charIt);
}
else
{
_com_error err(hr);
SendError(std::string("Could not unregister from characteristic ").append(BLEUtils::GUIDToString(addressGUID)).append(" ").append(BLEUtils::ToNarrow(err.ErrorMessage())));
// Next element!
++charIt;
}
}
else
{
// Next element!
++charIt;
}
}
if (CloseHandle(cservice->deviceHandle))
{
servIt = connectedServices.erase(servIt);
delete cservice;
disconnectedService = true;
}
else
{
SendError(std::string("Could not close handle to device ").append(BLEUtils::GUIDToString(addressGUID)));
}
}
else
{
++servIt;
}
}
return disconnectedService;
}
// --------------------------------------------------------------------------
// Retrieves the descriptors associated with a characteristic
// --------------------------------------------------------------------------
std::vector<BTH_LE_GATT_DESCRIPTOR> GetGATTDescriptors(HANDLE serviceHandle, PBTH_LE_GATT_CHARACTERISTIC characteristic)
{
DebugLog(std::string("GetGATTDescriptors: ").append(BLEUtils::BTHLEGUIDToString(characteristic->CharacteristicUuid)));
std::vector<BTH_LE_GATT_DESCRIPTOR> ret;
PBTH_LE_GATT_DESCRIPTOR descriptorsBuffer = nullptr;
USHORT descriptorsCount = 0;
HRESULT hr = S_OK;
while ((hr = BluetoothGATTGetDescriptors(serviceHandle, characteristic, descriptorsCount, descriptorsBuffer, &descriptorsCount, BLUETOOTH_GATT_FLAG_NONE)) != S_OK)
{
if (hr == HRESULT_FROM_WIN32(ERROR_MORE_DATA))
{
// Change the buffer size.
ret.resize(descriptorsCount);
// And have the method write directly into the vector!
descriptorsBuffer = ret.data();
}
else
{
_com_error err(hr);
SendError(std::string("Could not retrieve characteristic descriptors: ").append(BLEUtils::ToNarrow(err.ErrorMessage())));
break;
}
}
return ret;
}
// --------------------------------------------------------------------------
// Retrieves a descriptor's value, allocates memory because the data has variable size!
// --------------------------------------------------------------------------
PBTH_LE_GATT_DESCRIPTOR_VALUE AllocAndReadDescriptor(HANDLE serviceHandle, PBTH_LE_GATT_DESCRIPTOR descriptor)
{
DebugLog(std::string("AllocAndReadDescriptor: ").append(BLEUtils::BTHLEGUIDToString(descriptor->DescriptorUuid)));
// Determine Characteristic Value Buffer Size
USHORT descValueDataSize = 0;
PBTH_LE_GATT_DESCRIPTOR_VALUE pDescValueBuffer = nullptr;
HRESULT hr = S_OK;
while ((hr = BluetoothGATTGetDescriptorValue(serviceHandle, descriptor, (ULONG)descValueDataSize, pDescValueBuffer, &descValueDataSize, BLUETOOTH_GATT_FLAG_NONE)) != S_OK)
{
if (hr == HRESULT_FROM_WIN32(ERROR_MORE_DATA))
{
free(pDescValueBuffer);
pDescValueBuffer = (PBTH_LE_GATT_DESCRIPTOR_VALUE)malloc(descValueDataSize);
if (pDescValueBuffer != nullptr)
{
RtlZeroMemory(pDescValueBuffer, descValueDataSize);
pDescValueBuffer->DataSize = descValueDataSize;
}
else
{
SendOutOfMemoryError(descValueDataSize);
break;
}
}
else
{
free(pDescValueBuffer);
pDescValueBuffer = nullptr;
_com_error err(hr);
SendError(std::string("Could not get descriptor value ").append(BLEUtils::BTHLEGUIDToString(descriptor->DescriptorUuid)).append(" value: ").append(BLEUtils::ToNarrow(err.ErrorMessage())));
break;
}
}
return pDescValueBuffer;
}
// --------------------------------------------------------------------------
// Logs some info from the mono side
// --------------------------------------------------------------------------
void _winBluetoothLELog(const char* message)
{
DebugLog(message);
}
// --------------------------------------------------------------------------
// Initialize the bluetooth 'stack'
// --------------------------------------------------------------------------
void _winBluetoothLEInitialize(bool asCentral, bool asPeripheral)
{
SendBluetoothMessage("Initialized");
}
// --------------------------------------------------------------------------
// Clean up!
// --------------------------------------------------------------------------
void _winBluetoothLEDeInitialize()
{
LogToFile("DeInitialized");
_winBluetoothLEDisconnectAll();
if (sendMessageCallback != NULL)
{
sendMessageCallback("DeInitialized");
}
devices.clear();
services.clear();
connectedServices.clear();
registeredCharacteristics.clear();
const std::lock_guard<std::mutex> lock{ messageMutex };
messages.clear();
}
// --------------------------------------------------------------------------
// Pause sending messages back to the mono side
// --------------------------------------------------------------------------
void _winBluetoothLEPauseMessages(bool isPaused)
{
}
// --------------------------------------------------------------------------
// Scans all the bluetooth devices and notifies the mono side
// --------------------------------------------------------------------------
void _winBluetoothLEScanForPeripheralsWithServices(const char* serviceUUIDsString)
{
// Devices are managed by windows, so we don't need to 'remember' old devices
//devices.clear();
//services.clear();
//connectedServices.clear();
//registeredCharacteristics.clear();
// Scan for devices
ScanBLEInterfaces();
// Retrieve the devices with proper service UUID
if (serviceUUIDsString != nullptr)
{
DebugLog(std::string("_winBluetoothLEScanForPeripheralsWithServices: ").append(serviceUUIDsString));
auto uuids = BLEUtils::GenerateGUIDList(serviceUUIDsString);
notifyDevicesWithServices(uuids);
}
else
{
notifyAllDevices();
}
}
// --------------------------------------------------------------------------
// Lists all the currently connected devices
// --------------------------------------------------------------------------
void _winBluetoothLERetrieveListOfPeripheralsWithServices(const char* serviceUUIDsString)
{
if (serviceUUIDsString != nullptr)
{
DebugLog(std::string("_winBluetoothLERetrieveListOfPeripheralsWithServices: ").append(serviceUUIDsString));
auto uuids = BLEUtils::GenerateGUIDList(serviceUUIDsString);
notifyConnectedServices(uuids);
}
else
{
notifyAllConnected();
}
}
// --------------------------------------------------------------------------
// Stops scanning for bluetooth devices
// --------------------------------------------------------------------------
void _winBluetoothLEStopScan()
{
// Nothing to do for now, scanning is handled by windows
}
// --------------------------------------------------------------------------
// Connects to a given device and list services/characteristics
// --------------------------------------------------------------------------
void _winBluetoothLEConnectToPeripheral(const char* address)
{
if (address != nullptr)
{
DebugLog(std::string("_winBluetoothLEConnectToPeripheral: ").append(address));
// Iterate all the services for the given device
bool firstService = true;
GUID addressGUID = BLEUtils::StringToGUID(address);
for (auto servIt = services.begin(); servIt != services.end(); ++servIt)
{
auto service = *servIt;
if (service->containerId == addressGUID)
{
// Open a handle to the peripheral, and scan the services and characteristics
HANDLE serviceHandle = CreateFile(BLEUtils::ToWide(service->path.data()).data(), GENERIC_WRITE | GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, NULL);
if (serviceHandle != INVALID_HANDLE_VALUE)
{
// Remember we connected to the device, so we can clean up later!
auto connInfo = new BLEConnectedServiceInfo();
connInfo->service = service;
connInfo->deviceHandle = serviceHandle;
connectedServices.push_back(connInfo);
// Notify that we connected to a service!
if (firstService)
{
firstService = false;
std::string connectedMessage = "ConnectedPeripheral~";
connectedMessage.append(address);
SendBluetoothMessage(connectedMessage);
}
// Get GATT service ids and characteristics
if (GetGATTService(serviceHandle, connInfo->gattService))
{
// Check that the GATT service ID matches the service ID
auto gattServiceUuidString = BLEUtils::BTHLEGUIDToString(connInfo->gattService.ServiceUuid);
if (connInfo->gattService.ServiceUuid == service->id)
{
// Notify that we indeed got the GATT service info!
std::string discoveredServiceMessage = "DiscoveredService~";
discoveredServiceMessage.append(address);
discoveredServiceMessage.append("~");
discoveredServiceMessage.append(gattServiceUuidString);
SendBluetoothMessage(discoveredServiceMessage);
// Scan characteristics now!
connInfo->characteristics = GetGATTCharacteristics(serviceHandle, connInfo->gattService);
if (connInfo->characteristics.size() > 0)
{
for (auto& characteristic : connInfo->characteristics)
{
auto gattCharacteristicUuidString = BLEUtils::BTHLEGUIDToString(characteristic.CharacteristicUuid);
// Notify that we got characteristic info
std::string discoveredCharacteristicMessage = "DiscoveredCharacteristic~";
discoveredCharacteristicMessage.append(address);
discoveredCharacteristicMessage.append("~");
discoveredCharacteristicMessage.append(gattServiceUuidString);
discoveredCharacteristicMessage.append("~");
discoveredCharacteristicMessage.append(gattCharacteristicUuidString);
SendBluetoothMessage(discoveredCharacteristicMessage);
}
}
else
{
SendError(std::string("Device ").append(address).append(" reported 0 characteristics."));
}
}
else
{
SendError(std::string("GATT service id ").append(gattServiceUuidString).append(" does not match service id ").append(BLEUtils::BTHLEGUIDToString(service->id)));
}
}
// No matter what we're done looking through the services
return;
}
}
}
if (firstService)
{
SendError(std::string("Did not find any service for device ").append(address));
}
}
else
{
SendError(std::string("Can't connect to Null device address"));
}
}
// --------------------------------------------------------------------------
// Disconnects from a given device
// --------------------------------------------------------------------------
void _winBluetoothLEDisconnectPeripheral(const char* address)
{
if (address != nullptr)
{
DebugLog(std::string("_winBluetoothLEDisconnectPeripheral: ").append(address));
// Disconnect all services associated with this device
GUID addressGUID = BLEUtils::StringToGUID(address);
if (DisconnectServicesForDevice(addressGUID))
{