-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathusb_monitor.cpp
More file actions
89 lines (69 loc) · 2.31 KB
/
usb_monitor.cpp
File metadata and controls
89 lines (69 loc) · 2.31 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
#include "usb_monitor.h"
#include "device_info.h"
#include "logger.h"
#include <initguid.h>
#include <Usbiodef.h>
// GUID_DEVINTERFACE_USB_DEVICE is defined in Usbiodef.h
USBMonitor::USBMonitor() = default;
USBMonitor::~USBMonitor() {
stop();
}
bool USBMonitor::start(HWND hwnd) {
DEV_BROADCAST_DEVICEINTERFACE notificationFilter;
ZeroMemory(¬ificationFilter, sizeof(notificationFilter));
notificationFilter.dbcc_size = sizeof(DEV_BROADCAST_DEVICEINTERFACE);
notificationFilter.dbcc_devicetype = DBT_DEVTYP_DEVICEINTERFACE;
notificationFilter.dbcc_classguid = GUID_DEVINTERFACE_USB_DEVICE;
m_notificationHandle = RegisterDeviceNotificationW(
hwnd,
¬ificationFilter,
DEVICE_NOTIFY_WINDOW_HANDLE);
if (!m_notificationHandle) {
LOG_ERROR(L"Failed to register for USB device notifications");
return false;
}
return true;
}
void USBMonitor::stop() {
if (m_notificationHandle) {
UnregisterDeviceNotification(m_notificationHandle);
m_notificationHandle = nullptr;
}
}
void USBMonitor::setCallback(DeviceCallback callback) {
m_callback = callback;
}
void USBMonitor::processDeviceChange(WPARAM wParam, LPARAM lParam) {
if (wParam != DBT_DEVICEARRIVAL && wParam != DBT_DEVICEREMOVECOMPLETE) {
return;
}
PDEV_BROADCAST_HDR header = reinterpret_cast<PDEV_BROADCAST_HDR>(lParam);
if (!header || header->dbch_devicetype != DBT_DEVTYP_DEVICEINTERFACE) {
return;
}
PDEV_BROADCAST_DEVICEINTERFACE_W devInterface =
reinterpret_cast<PDEV_BROADCAST_DEVICEINTERFACE_W>(lParam);
std::wstring devicePath = devInterface->dbcc_name;
bool connected = (wParam == DBT_DEVICEARRIVAL);
// Get device info
USBDeviceInfo deviceInfo = getUSBDeviceFromPath(devicePath);
if (connected) {
LOG_USB_CONNECTED(deviceInfo.getDisplayString());
} else {
LOG_USB_DISCONNECTED(deviceInfo.getDisplayString());
}
if (m_callback) {
m_callback(connected, devicePath);
}
}
void USBMonitor::listCurrentDevices() {
auto devices = enumerateUSBDevices();
LOG_SECTION(L"USB DEVICES");
if (devices.empty()) {
LOG_INFO(L"No USB devices found");
return;
}
for (const auto& device : devices) {
LOG_USB(device.getDisplayString());
}
}