-
Notifications
You must be signed in to change notification settings - Fork 14
/
Copy pathusb_com_locator.h
1074 lines (904 loc) · 33.9 KB
/
usb_com_locator.h
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
//
// usb_com_locator.h
// Copyright (C) 2019 Marius Greuel. All rights reserved.
//
#pragma once
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#include <initguid.h>
#include <devpkey.h>
#include <setupapi.h>
#include <winioctl.h>
#include <cassert>
#include <cstdarg>
#include <cwchar>
#include <cwctype>
#include <iostream>
#include <memory>
#include <stdexcept>
#include <string>
#include <vector>
#pragma comment(lib, "setupapi.lib")
namespace UsbComLocator
{
enum class MessageLevel
{
Error,
Info,
Verbose,
Debug,
};
struct IConsole
{
virtual void WriteLine(MessageLevel level, const std::string& message) = 0;
};
class Win32
{
public:
static std::wstring CreateMessageFromHResult(long hr)
{
std::wstring message;
LPWSTR pszMessage = nullptr;
DWORD dwChars = FormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM, nullptr, hr, 0, (LPWSTR)&pszMessage, 0, nullptr);
if (dwChars > 0 && pszMessage != nullptr)
{
if (dwChars > 0 && pszMessage[dwChars - 1] == '\n')
dwChars--;
if (dwChars > 0 && pszMessage[dwChars - 1] == '\r')
dwChars--;
message = std::wstring(pszMessage, dwChars);
LocalFree(pszMessage);
}
return message;
}
};
class Handle
{
public:
Handle() = default;
~Handle()
{
Close();
}
Handle(const Handle&) = delete;
Handle& operator=(const Handle& other) = delete;
Handle(Handle&&) = default;
Handle& operator=(Handle&& other) = default;
operator HANDLE() const noexcept
{
return m_handle;
}
Handle& operator=(HANDLE handle)
{
Close();
m_handle = handle;
return *this;
}
void Close() noexcept
{
if (m_handle != nullptr)
{
CloseHandle(m_handle);
m_handle = nullptr;
}
}
void Attach(HANDLE handle) noexcept
{
assert(m_handle == nullptr);
m_handle = handle;
}
HANDLE Detach() noexcept
{
HANDLE handle = m_handle;
m_handle = nullptr;
return handle;
}
protected:
HANDLE m_handle = nullptr;
};
class Encoding
{
public:
static std::string ToAnsi(const std::wstring& text)
{
std::string str;
if (!text.empty())
{
int chars = ::WideCharToMultiByte(CP_ACP, 0, text.c_str(), static_cast<int>(text.size()), nullptr, 0, nullptr, nullptr);
if (chars == 0)
{
return std::string();
}
str.resize(chars);
chars = ::WideCharToMultiByte(CP_ACP, 0, text.c_str(), static_cast<int>(text.size()), &str[0], static_cast<int>(str.size()), nullptr, nullptr);
if (chars == 0)
{
return std::string();
}
}
return str;
}
static std::wstring ToUnicode(const std::string& text)
{
std::wstring str;
if (!text.empty())
{
int chars = ::MultiByteToWideChar(CP_ACP, 0, text.c_str(), static_cast<int>(text.size()), nullptr, 0);
if (chars == 0)
{
return std::wstring();
}
str.resize(chars);
chars = ::MultiByteToWideChar(CP_ACP, 0, text.c_str(), static_cast<int>(text.size()), &str[0], static_cast<int>(str.size()));
if (chars == 0)
{
return std::wstring();
}
}
return str;
}
};
class RegistryKey
{
public:
RegistryKey() = default;
RegistryKey(HKEY hKey) : m_hKey(hKey)
{
}
~RegistryKey()
{
Close();
}
RegistryKey(const RegistryKey&) = delete;
RegistryKey& operator=(const RegistryKey& other) = delete;
RegistryKey(RegistryKey&&) = default;
RegistryKey& operator=(RegistryKey&& other) = default;
operator HKEY() const noexcept
{
return m_hKey;
}
void Close() noexcept
{
if (m_hKey != nullptr)
{
RegCloseKey(m_hKey);
m_hKey = nullptr;
}
}
void Attach(HKEY handle) noexcept
{
assert(m_hKey == nullptr);
m_hKey = handle;
}
HKEY Detach() noexcept
{
HKEY handle = m_hKey;
m_hKey = nullptr;
return handle;
}
HRESULT QueryValue(LPCWSTR pszValueName, std::wstring& value) noexcept
{
DWORD dwType = 0;
DWORD dwRequiredSize = 0;
LSTATUS nError = RegQueryValueExW(m_hKey, pszValueName, nullptr, &dwType, nullptr, &dwRequiredSize);
if (nError != ERROR_SUCCESS)
{
return HRESULT_FROM_WIN32(nError);
}
if (dwType != REG_SZ && dwType != REG_EXPAND_SZ)
{
return HRESULT_FROM_WIN32(ERROR_INVALID_DATA);
}
std::vector<uint8_t> buffer(dwRequiredSize);
nError = RegQueryValueExW(m_hKey, pszValueName, nullptr, &dwType, buffer.data(), &dwRequiredSize);
if (nError != ERROR_SUCCESS)
{
return HRESULT_FROM_WIN32(nError);
}
LPCWSTR pszValue = reinterpret_cast<LPCWSTR>(buffer.data());
DWORD dwChars = dwRequiredSize / sizeof(WCHAR);
if (dwChars > 0 && pszValue[dwChars - 1] == 0)
{
dwChars--;
}
value = std::wstring(pszValue, dwChars);
return S_OK;
}
protected:
HKEY m_hKey = nullptr;
};
class DeviceInfo : public SP_DEVINFO_DATA
{
public:
DeviceInfo()
{
(SP_DEVINFO_DATA&)(*this) = { sizeof(SP_DEVINFO_DATA) };
}
DeviceInfo(const DeviceInfo&) = delete;
DeviceInfo& operator=(const DeviceInfo& other) = delete;
DeviceInfo(DeviceInfo&&) = delete;
DeviceInfo& operator=(DeviceInfo&& other) = delete;
public:
HRESULT Open(HDEVINFO hDeviceInfoSet, LPCWSTR pszDeviceInstanceId, HWND hwndParent = nullptr, DWORD dwOpenFlags = 0)
{
if (!SetupDiOpenDeviceInfoW(hDeviceInfoSet, pszDeviceInstanceId, hwndParent, dwOpenFlags, this))
{
return HRESULT_FROM_WIN32(GetLastError());
}
return S_OK;
}
HRESULT GetProperty(HDEVINFO hDeviceInfoSet, const DEVPROPKEY* key, bool& value)
{
DEVPROP_BOOLEAN buffer{};
DEVPROPTYPE type = DEVPROP_TYPE_EMPTY;
DWORD dwRequiredSize = 0;
if (!SetupDiGetDevicePropertyW(hDeviceInfoSet, this, key, &type, reinterpret_cast<PBYTE>(&buffer), sizeof(buffer), &dwRequiredSize, 0))
{
return HRESULT_FROM_WIN32(GetLastError());
}
if (type != DEVPROP_TYPE_BOOLEAN)
{
return HRESULT_FROM_WIN32(ERROR_INVALID_DATATYPE);
}
value = buffer != DEVPROP_FALSE;
return S_OK;
}
HRESULT GetProperty(HDEVINFO hDeviceInfoSet, const DEVPROPKEY* key, uint32_t& value)
{
uint32_t buffer{};
DEVPROPTYPE type = DEVPROP_TYPE_EMPTY;
DWORD dwRequiredSize = 0;
if (!SetupDiGetDevicePropertyW(hDeviceInfoSet, this, key, &type, reinterpret_cast<PBYTE>(&buffer), sizeof(buffer), &dwRequiredSize, 0))
{
return HRESULT_FROM_WIN32(GetLastError());
}
if (type != DEVPROP_TYPE_UINT32)
{
return HRESULT_FROM_WIN32(ERROR_INVALID_DATATYPE);
}
value = buffer;
return S_OK;
}
HRESULT GetProperty(HDEVINFO hDeviceInfoSet, const DEVPROPKEY* key, GUID& value)
{
GUID buffer{};
DEVPROPTYPE type = DEVPROP_TYPE_EMPTY;
DWORD dwRequiredSize = 0;
if (!SetupDiGetDevicePropertyW(hDeviceInfoSet, this, key, &type, reinterpret_cast<PBYTE>(&buffer), sizeof(buffer), &dwRequiredSize, 0))
{
DWORD dwError = GetLastError();
if (dwError != ERROR_INSUFFICIENT_BUFFER)
{
return HRESULT_FROM_WIN32(dwError);
}
}
if (type != DEVPROP_TYPE_GUID)
{
return HRESULT_FROM_WIN32(ERROR_INVALID_DATATYPE);
}
value = buffer;
return S_OK;
}
HRESULT GetProperty(HDEVINFO hDeviceInfoSet, const DEVPROPKEY* key, std::wstring& value)
{
DEVPROPTYPE type = DEVPROP_TYPE_EMPTY;
DWORD dwRequiredSize = 0;
if (!SetupDiGetDevicePropertyW(hDeviceInfoSet, this, key, &type, nullptr, 0, &dwRequiredSize, 0))
{
DWORD dwError = GetLastError();
if (dwError != ERROR_INSUFFICIENT_BUFFER)
{
return HRESULT_FROM_WIN32(dwError);
}
}
if (type != DEVPROP_TYPE_STRING)
{
return HRESULT_FROM_WIN32(ERROR_INVALID_DATATYPE);
}
std::vector<uint8_t> buffer(dwRequiredSize);
if (!SetupDiGetDevicePropertyW(hDeviceInfoSet, this, key, &type, buffer.data(), dwRequiredSize, nullptr, 0))
{
return HRESULT_FROM_WIN32(GetLastError());
}
LPCWSTR pszValue = reinterpret_cast<LPCWSTR>(buffer.data());
DWORD dwChars = dwRequiredSize / sizeof(WCHAR);
if (dwChars > 0 && pszValue[dwChars - 1] == 0)
{
dwChars--;
}
value = std::wstring(pszValue, dwChars);
return S_OK;
}
HRESULT GetProperty(HDEVINFO hDeviceInfoSet, const DEVPROPKEY* key, std::vector<std::wstring>& values)
{
DEVPROPTYPE type = DEVPROP_TYPE_EMPTY;
DWORD dwRequiredSize = 0;
if (!SetupDiGetDevicePropertyW(hDeviceInfoSet, this, key, &type, nullptr, 0, &dwRequiredSize, 0))
{
DWORD dwError = GetLastError();
if (dwError != ERROR_INSUFFICIENT_BUFFER)
{
return HRESULT_FROM_WIN32(dwError);
}
}
if (type != DEVPROP_TYPE_STRING_LIST)
{
return HRESULT_FROM_WIN32(ERROR_INVALID_DATATYPE);
}
std::vector<uint8_t> buffer(dwRequiredSize);
if (!SetupDiGetDevicePropertyW(hDeviceInfoSet, this, key, &type, buffer.data(), dwRequiredSize, nullptr, 0))
{
return HRESULT_FROM_WIN32(GetLastError());
}
auto data = reinterpret_cast<const wchar_t*>(buffer.data());
while (*data != 0)
{
values.push_back(data);
data += wcslen(data) + 1;
}
return S_OK;
}
HRESULT GetRegistryValue(HDEVINFO hDeviceInfoSet, LPCWSTR pszValueName, std::wstring& value)
{
HKEY hKey = SetupDiOpenDevRegKey(hDeviceInfoSet, this, DICS_FLAG_GLOBAL, 0, DIREG_DEV, KEY_READ);
if (hKey == INVALID_HANDLE_VALUE)
{
return HRESULT_FROM_WIN32(GetLastError());
}
RegistryKey key(hKey);
return key.QueryValue(pszValueName, value);
}
};
class DeviceInfoSet
{
public:
DeviceInfoSet() = default;
DeviceInfoSet(const DeviceInfoSet&) = delete;
DeviceInfoSet& operator=(const DeviceInfoSet& other) = delete;
DeviceInfoSet(DeviceInfoSet&&) = delete;
DeviceInfoSet& operator=(DeviceInfoSet&& other) = delete;
~DeviceInfoSet()
{
Destroy();
}
public:
operator HDEVINFO() const noexcept
{
return m_hDeviceInfoSet;
}
public:
HRESULT Create(const GUID* classGuid, HWND hwndParent)
{
Destroy();
HDEVINFO hDeviceInfoSet = SetupDiCreateDeviceInfoList(classGuid, hwndParent);
if (hDeviceInfoSet == INVALID_HANDLE_VALUE)
{
return HRESULT_FROM_WIN32(GetLastError());
}
m_hDeviceInfoSet = hDeviceInfoSet;
return S_OK;
}
HRESULT GetClassDevs(const GUID* classGuid, PCWSTR pszEnumerator, HWND hWndParent, DWORD dwFlags)
{
Destroy();
HDEVINFO hDeviceInfoSet = SetupDiGetClassDevsW(classGuid, pszEnumerator, hWndParent, dwFlags);
if (hDeviceInfoSet == INVALID_HANDLE_VALUE)
{
return HRESULT_FROM_WIN32(GetLastError());
}
m_hDeviceInfoSet = hDeviceInfoSet;
return S_OK;
}
void Destroy()
{
if (m_hDeviceInfoSet != INVALID_HANDLE_VALUE)
{
SetupDiDestroyDeviceInfoList(m_hDeviceInfoSet);
m_hDeviceInfoSet = INVALID_HANDLE_VALUE;
}
}
private:
HDEVINFO m_hDeviceInfoSet = INVALID_HANDLE_VALUE;
};
class Device
{
public:
Device() = default;
Device(const Device&) = delete;
Device& operator=(const Device& other) = delete;
Device(Device&&) = delete;
Device& operator=(Device&& other) = delete;
public:
bool IsBootloaderMode() const
{
return !m_isCompositeDevice;
}
HRESULT Open(
DWORD dwDesiredAccess = GENERIC_READ | GENERIC_WRITE,
DWORD dwFlagsAndAttributes = FILE_ATTRIBUTE_NORMAL,
LPSECURITY_ATTRIBUTES lpSecurityAttributes = nullptr)
{
HANDLE hDevice = CreateFileW(
(L"\\\\.\\" + m_port).c_str(),
dwDesiredAccess,
0,
lpSecurityAttributes,
OPEN_EXISTING,
dwFlagsAndAttributes,
nullptr);
if (hDevice == INVALID_HANDLE_VALUE)
{
return HRESULT_FROM_WIN32(GetLastError());
}
m_hDevice = hDevice;
return S_OK;
}
void Close()
{
m_hDevice.Close();
}
HRESULT WaitForPortAvailability(uint32_t retries = 100, uint32_t timeout = 10)
{
while (true)
{
HRESULT hr = Open();
if (SUCCEEDED(hr))
{
Close();
return S_OK;
}
if (retries == 0)
{
return hr;
}
Sleep(timeout);
retries--;
}
}
HRESULT Reset()
{
HRESULT hr = Open();
if (FAILED(hr))
{
return hr;
}
EscapeCommFunction(m_hDevice, CLRDTR);
DCB dcb = { sizeof(DCB) };
dcb.BaudRate = CBR_1200;
dcb.fDtrControl = DTR_CONTROL_DISABLE;
dcb.fRtsControl = RTS_CONTROL_DISABLE;
dcb.ByteSize = 8;
dcb.Parity = NOPARITY;
dcb.StopBits = ONESTOPBIT;
SetCommState(m_hDevice, &dcb);
Close();
return S_OK;
}
public:
std::wstring m_instanceId;
std::wstring m_port;
std::wstring m_location;
std::wstring m_productName;
bool m_isPresent = false;
bool m_isCompositeDevice = false;
uint16_t m_vid = 0;
uint16_t m_pid = 0;
Handle m_hDevice;
};
class Enumerator
{
public:
Enumerator() = default;
Enumerator(const Enumerator&) = delete;
Enumerator& operator=(const Enumerator& other) = delete;
Enumerator(Enumerator&&) = delete;
Enumerator& operator=(Enumerator&& other) = delete;
public:
std::vector<std::shared_ptr<Device>>& GetDevices() { return m_devices; }
public:
HRESULT EnumerateDevices(bool includeUnpluggedDevices = false)
{
m_devices.clear();
DeviceInfoSet deviceInfoSet;
HRESULT hr = deviceInfoSet.GetClassDevs(&GUID_DEVINTERFACE_COMPORT, nullptr, nullptr, (includeUnpluggedDevices ? 0 : DIGCF_PRESENT) | DIGCF_DEVICEINTERFACE);
if (FAILED(hr))
return hr;
for (DWORD index = 0; ; index++)
{
DeviceInfo deviceInfo;
if (!SetupDiEnumDeviceInfo(deviceInfoSet, index, &deviceInfo))
{
DWORD dwError = GetLastError();
if (dwError != ERROR_NO_MORE_ITEMS)
{
return HRESULT_FROM_WIN32(dwError);
}
break;
}
auto device = std::make_shared<Device>();
if (SUCCEEDED(deviceInfo.GetProperty(deviceInfoSet, &DEVPKEY_Device_InstanceId, device->m_instanceId)))
{
ParseVidPid(device->m_instanceId.c_str(), L"VID_", device->m_vid);
ParseVidPid(device->m_instanceId.c_str(), L"PID_", device->m_pid);
deviceInfo.GetProperty(deviceInfoSet, &DEVPKEY_Device_IsPresent, device->m_isPresent);
deviceInfo.GetProperty(deviceInfoSet, &DEVPKEY_Device_BusReportedDeviceDesc, device->m_productName);
deviceInfo.GetRegistryValue(deviceInfoSet, L"PortName", device->m_port);
device->m_isCompositeDevice = IsCompositeDevice(device->m_instanceId.c_str());
if (device->m_isCompositeDevice)
{
GetCompositeDevicePortLocation(deviceInfoSet, deviceInfo, device->m_location);
}
else
{
deviceInfo.GetProperty(deviceInfoSet, &DEVPKEY_Device_LocationInfo, device->m_location);
}
m_devices.push_back(std::move(device));
}
}
return S_OK;
}
bool ParseVidPid(_In_z_ wchar_t const* buffer, wchar_t const* prefix, uint16_t& value)
{
wchar_t const* match = wcsstr(buffer, prefix);
if (match == nullptr)
{
return false;
}
match += wcslen(prefix);
wchar_t* endptr = nullptr;
value = static_cast<uint16_t>(std::wcstoul(match, &endptr, 16));
return endptr == match + 4;
}
private:
HRESULT GetCompositeDevicePortLocation(HDEVINFO hDeviceInfoSet, DeviceInfo& deviceInfo, std::wstring& location)
{
DeviceInfoSet deviceInfoSet;
HRESULT hr = deviceInfoSet.Create(nullptr, nullptr);
if (FAILED(hr))
{
return hr;
}
std::wstring parentDeviceInstanceId;
hr = deviceInfo.GetProperty(hDeviceInfoSet, &DEVPKEY_Device_Parent, parentDeviceInstanceId);
if (FAILED(hr))
{
return hr;
}
DeviceInfo parentDeviceInfo;
hr = parentDeviceInfo.Open(deviceInfoSet, parentDeviceInstanceId.c_str());
if (FAILED(hr))
{
return hr;
}
hr = parentDeviceInfo.GetProperty(deviceInfoSet, &DEVPKEY_Device_LocationInfo, location);
if (FAILED(hr))
{
return hr;
}
return S_OK;
}
static bool IsCompositeDevice(LPCWSTR deviceInstanceId)
{
return wcsstr(deviceInstanceId, L"&MI_") != nullptr;
}
private:
std::vector<std::shared_ptr<Device>> m_devices;
};
class Locator
{
public:
struct Options
{
bool WaitForDevice = true;
bool FindRelatedDevices = true;
bool AutoReset = true;
uint32_t Retries = 0xFFFFFFFF;
uint32_t RetryIntervall = 100;
};
public:
Locator(IConsole* console = nullptr) : m_console(console)
{
}
Locator(const Locator&) = delete;
Locator& operator=(const Locator& other) = delete;
Locator(Locator&&) = delete;
Locator& operator=(Locator&& other) = delete;
public:
std::string FindPortForDevice(const std::string& deviceId, const Options* options = nullptr)
{
auto device = FindDevice(Encoding::ToUnicode(deviceId), options);
if (device == nullptr)
return std::string();
return Encoding::ToAnsi(device->m_port);
}
std::wstring FindPortForDevice(const std::wstring& deviceId, const Options* options = nullptr)
{
auto device = FindDevice(deviceId, options);
if (device == nullptr)
return std::wstring();
return device->m_port;
}
std::shared_ptr<Device> FindDevice(const std::string& deviceId, const Options* options = nullptr)
{
return FindDevice(Encoding::ToUnicode(deviceId), options);
}
std::shared_ptr<Device> FindDevice(const std::wstring& deviceId, const Options* options = nullptr)
{
if (options == nullptr)
{
static Options defaults;
options = &defaults;
}
uint32_t retries = options->Retries;
while (true)
{
m_enumerator.EnumerateDevices(true);
auto devices = FindDevices(deviceId, options->FindRelatedDevices);
if (devices.size() == 0)
{
throw std::runtime_error("Device not found.");
}
auto device = devices[0];
if (device->m_isPresent)
{
PrintMessage(MessageLevel::Verbose, "Found device at port '%ws'", device->m_port.c_str());
PrintDeviceProperties(device);
HRESULT hr = device->WaitForPortAvailability(options->Retries, options->RetryIntervall);
if (FAILED(hr))
{
PrintMessage(MessageLevel::Error, "Failed to open serial port: %ws", Win32::CreateMessageFromHResult(hr).c_str());
throw std::runtime_error("Failed to open serial port.");
}
if (device->IsBootloaderMode() || !options->AutoReset)
{
return device;
}
PrintMessage(MessageLevel::Info, "Entering bootloader mode...");
hr = device->Reset();
if (FAILED(hr))
{
PrintMessage(MessageLevel::Error, "Failed to reset device: %ws", Win32::CreateMessageFromHResult(hr).c_str());
throw std::runtime_error("Failed to reset device.");
}
retries = options->Retries;
while (true)
{
m_enumerator.EnumerateDevices(true);
auto relatedDevices = FindRelatedDevices(devices);
if (relatedDevices.size() > 0)
{
auto relatedDevice = relatedDevices[0];
if (relatedDevice->m_isPresent)
{
PrintMessage(MessageLevel::Verbose, "Found device at port '%ws'", relatedDevice->m_port.c_str());
PrintDeviceProperties(relatedDevice);
hr = relatedDevice->WaitForPortAvailability(options->Retries, options->RetryIntervall);
if (FAILED(hr))
{
PrintMessage(MessageLevel::Error, "Failed to open serial port: %ws", Win32::CreateMessageFromHResult(hr).c_str());
throw std::runtime_error("Failed to open serial port.");
}
return relatedDevice;
}
}
if (!options->WaitForDevice || retries == 0)
{
return nullptr;
}
Sleep(options->RetryIntervall);
retries--;
}
}
if (!options->WaitForDevice || retries == 0)
{
return nullptr;
}
if (retries == options->Retries)
{
PrintMessage(MessageLevel::Info, "No device present, retrying every %ums...", options->RetryIntervall);
}
Sleep(options->RetryIntervall);
retries--;
}
}
void LocateAllDevices()
{
PrintMessage(MessageLevel::Verbose, "Enumerating devices...");
m_enumerator.EnumerateDevices(true);
for (auto& device : m_enumerator.GetDevices())
{
PrintMessage(MessageLevel::Info, "Found device: %ws", device->m_instanceId.c_str());
PrintDeviceProperties(device);
}
}
private:
std::vector<std::shared_ptr<Device>> FindDevices(const std::wstring& deviceId, bool findRelatedDevices = false)
{
uint32_t comPort = 0;
uint16_t vid = 0;
uint16_t pid = 0;
if (swscanf_s(ToUpper(deviceId).c_str(), L"COM%u", &comPort) == 1)
{
auto devices = FindDevicesByPort(deviceId);
if (devices.size() > 0)
{
// 1) Return plugged-in devices with exact COM port match.
return devices;
}
auto unpluggedDevices = FindDevicesByPort(deviceId, true);
if (findRelatedDevices)
{
auto relatedDevices = FindRelatedDevices(unpluggedDevices);
if (relatedDevices.size() > 0)
{
// 2) Return plugged-in devices related to the COM port.
return relatedDevices;
}
}
// 3) Return unplugged devices with exact COM port match.
return unpluggedDevices;
}
else if (swscanf_s(ToUpper(deviceId).c_str(), L"USB:%hX:%hX", &vid, &pid) == 2)
{
auto devices = FindDevicesByUsbId(vid, pid);
if (devices.size() > 0)
{
// 1) Return plugged-in devices with exact USB VID:PID match.
return devices;
}
auto unpluggedDevices = FindDevicesByUsbId(vid, pid, std::wstring(), true);
if (findRelatedDevices)
{
// 2) Return plugged-in devices with related USB VID:PID and HUB location.
auto relatedDevices = FindRelatedDevices(unpluggedDevices);
if (relatedDevices.size() > 0)
{
return relatedDevices;
}
// 3) Return plugged-in devices with related USB VID:PID (bootloader device never plugged-in).
relatedDevices = FindRelatedDevices(vid, pid);
if (relatedDevices.size() > 0)
{
return relatedDevices;
}
}
// 4) Return unplugged devices with exact USB VID:PID match.
return unpluggedDevices;
}
else
{
throw std::runtime_error("Invalid device specifier.");
}
}
std::vector<std::shared_ptr<Device>> FindDevicesByPort(const std::wstring& port, bool includeUnpluggedDevices = false)
{
std::vector<std::shared_ptr<Device>> devices;
for (auto& device : m_enumerator.GetDevices())
{
if ((device->m_isPresent || includeUnpluggedDevices) &&
_wcsicmp(device->m_port.c_str(), port.c_str()) == 0)
{
devices.push_back(device);
}
}
return devices;
}
std::vector<std::shared_ptr<Device>> FindDevicesByUsbId(uint16_t vid, uint16_t pid, const std::wstring& location = std::wstring(), bool includeUnpluggedDevices = false)
{
std::vector<std::shared_ptr<Device>> devices;
for (auto& device : m_enumerator.GetDevices())
{
if ((device->m_isPresent || includeUnpluggedDevices) &&
device->m_vid == vid &&
device->m_pid == pid &&
(location.empty() || device->m_location == location))
{
devices.push_back(device);
}
}
return devices;
}
std::vector<std::shared_ptr<Device>> FindRelatedDevices(const std::vector<std::shared_ptr<Device>>& devices)
{
std::vector<std::shared_ptr<Device>> relatedDevices;
for (const auto& device : devices)
{
auto relatedPids = GetRelatedPids(device->m_pid, device->IsBootloaderMode());
for (auto relatedPid : relatedPids)
{
auto list = FindDevicesByUsbId(device->m_vid, relatedPid, device->m_location);
relatedDevices.insert(relatedDevices.end(), list.begin(), list.end());
}
}
return relatedDevices;
}
std::vector<std::shared_ptr<Device>> FindRelatedDevices(uint16_t vid, uint16_t pid)
{
std::vector<std::shared_ptr<Device>> relatedDevices;
auto relatedPids = GetRelatedPids(pid, true);
for (auto relatedPid : relatedPids)
{
auto list = FindDevicesByUsbId(vid, relatedPid);
relatedDevices.insert(relatedDevices.end(), list.begin(), list.end());
}
return relatedDevices;
}
static std::vector<uint16_t> GetRelatedPids(uint16_t pid, bool isBootloaderMode)
{
// Arduino boards with a direct USB connection (such as Leonardo or Micro)
// have one USB serial port for the bootloader and one for the sketch.
// Bootloader and sketch devices have the same VID but different PIDs.
// To find related PIDs (bootloader vs. sketch device), we use the following heuristics:
// Arduino, Adafruit, etc.:
// - Bootloader PID: PIDxxxx with the MSB cleared
// - Sketch PID: PIDxxxx with the MSB set
// Others, who did not understand the above (Sparkfun):
// - Bootloader PID: PIDxxxx
// - Sketch PID: PIDxxxx + 1
std::vector<uint16_t> relatedPids;
if (isBootloaderMode)