-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmonitor.rs
More file actions
348 lines (317 loc) · 10.5 KB
/
Copy pathmonitor.rs
File metadata and controls
348 lines (317 loc) · 10.5 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
//! Task 1:硬件与蓝牙断连实时监控 — 捕获 WM_DEVICECHANGE 并通过 Tauri Event 推送
use crate::events::DeviceEvent;
use crate::notify;
use crate::settings;
use crate::tray::{self, TrayLevel};
use crate::usb_storage;
use crate::utils::device_name;
use crate::utils::device_path::{is_transient_disconnect, parse_device_path, DeviceCategory};
use crate::utils::guid::{DEVINTERFACE_BLUETOOTH, DEVINTERFACE_USB_DEVICE};
use crate::utils::logging;
use chrono::Local;
use std::collections::HashMap;
use std::mem::size_of;
use std::sync::{Mutex, OnceLock};
use std::thread::{self, JoinHandle};
use std::time::{Duration, Instant};
use tauri::{AppHandle, Emitter};
use windows::core::PCWSTR;
use windows::Win32::Foundation::{HANDLE, HWND, LPARAM, LRESULT, WPARAM};
use windows::Win32::System::LibraryLoader::GetModuleHandleW;
use windows::Win32::UI::WindowsAndMessaging::{
CreateWindowExW, DefWindowProcW, DispatchMessageW, GetMessageW, PostQuitMessage,
RegisterClassW, RegisterDeviceNotificationW, TranslateMessage, UnregisterClassW, CS_HREDRAW,
CS_VREDRAW, DBT_DEVICEARRIVAL, DBT_DEVICEREMOVECOMPLETE, DBT_DEVTYP_DEVICEINTERFACE,
DEVICE_NOTIFY_WINDOW_HANDLE, DEV_BROADCAST_DEVICEINTERFACE_W, DEV_BROADCAST_HDR, HWND_MESSAGE,
WINDOW_EX_STYLE, WINDOW_STYLE, WM_DESTROY, WM_DEVICECHANGE, WNDCLASSW,
};
const CLASS_NAME: PCWSTR = windows::core::w!("ZeroTickDeviceMonitor");
static TRACKER: OnceLock<Mutex<DisconnectTracker>> = OnceLock::new();
static APP_HANDLE: OnceLock<AppHandle> = OnceLock::new();
struct DisconnectTracker {
pending: HashMap<String, Instant>,
}
impl DisconnectTracker {
fn new() -> Self {
Self {
pending: HashMap::new(),
}
}
fn record_disconnect(&mut self, path: &str) {
self.pending.insert(path.to_string(), Instant::now());
}
fn record_arrival(&mut self, path: &str) -> Option<std::time::Duration> {
self.pending.remove(path).map(|t| t.elapsed())
}
}
pub fn spawn(app: AppHandle) -> windows::core::Result<JoinHandle<()>> {
let _ = TRACKER.set(Mutex::new(DisconnectTracker::new()));
let _ = APP_HANDLE.set(app);
thread::Builder::new()
.name("zerotick-device-monitor".into())
.spawn(run_message_loop)
.map_err(|e| {
windows::core::Error::new(
windows::core::HRESULT::from_win32(windows::Win32::Foundation::ERROR_GEN_FAILURE.0),
format!("无法创建设备监控线程: {e}"),
)
})
}
fn emit_device_event(payload: DeviceEvent) {
if let Some(app) = APP_HANDLE.get() {
if let Err(e) = app.emit("device-event", &payload) {
logging::error(format!("emit device-event 失败: {e}"));
}
}
}
fn push_event(
event_type: &str,
category: DeviceCategory,
vid_pid: Option<String>,
device_path: String,
disconnect_ms: Option<u64>,
tray_level: TrayLevel,
tray_reason_id: &str,
) {
if category == DeviceCategory::Usb {
usb_storage::invalidate_diagnostic_cache();
}
let category_code = category.as_str().to_string();
let friendly_name = device_name::resolve(&device_path, vid_pid.as_deref());
let message = build_message(
event_type,
&category_code,
&friendly_name,
&vid_pid,
disconnect_ms,
);
if let Some(app) = APP_HANDLE.get() {
tray::set_level(app, tray_level, tray_reason_id);
}
let event = DeviceEvent {
timestamp: Local::now().to_rfc3339(),
event_type: event_type.to_string(),
category: category_code,
vid_pid,
device_path,
disconnect_ms,
message,
friendly_name,
};
emit_device_event(event.clone());
crate::history::append(&event);
if let Some(app) = APP_HANDLE.get() {
let locale = settings::get().locale;
let (title, body) = match event_type {
"transient_reconnect" => (
crate::i18n::notify_transient_title(&locale),
crate::i18n::format_device_notify(&locale, event_type, &event),
),
"remove" => (
crate::i18n::notify_disconnect_title(&locale),
crate::i18n::format_device_notify(&locale, event_type, &event),
),
_ => return,
};
notify::send_if_background(app, &title, &body);
}
}
fn build_message(
event_type: &str,
category: &str,
friendly_name: &Option<String>,
vid_pid: &Option<String>,
disconnect_ms: Option<u64>,
) -> String {
let label = friendly_name
.as_deref()
.or(vid_pid.as_deref())
.unwrap_or("unknown");
match event_type {
"transient_reconnect" => {
format!(
"[transient] [{category}] {label} — {}",
crate::i18n::format_duration_ms(disconnect_ms.unwrap_or(0))
)
}
"arrival" if disconnect_ms.is_some() => {
format!(
"[{category}] {label} — reconnect {}",
crate::i18n::format_duration_ms(disconnect_ms.unwrap_or(0))
)
}
"arrival" => format!("[{category}] {label} — arrival"),
"remove" => format!("[{category}] {label} — remove"),
_ => format!("[{category}] {label}"),
}
}
fn run_message_loop() {
if let Err(e) = run_message_loop_inner() {
logging::error(format!("设备监控线程异常退出: {e}"));
}
}
fn run_message_loop_inner() -> windows::core::Result<()> {
unsafe {
let hinstance = GetModuleHandleW(None)?;
let wc = WNDCLASSW {
lpfnWndProc: Some(device_wnd_proc),
hInstance: hinstance.into(),
lpszClassName: CLASS_NAME,
style: CS_HREDRAW | CS_VREDRAW,
..Default::default()
};
let _ = RegisterClassW(&wc);
let hwnd = CreateWindowExW(
WINDOW_EX_STYLE(0),
CLASS_NAME,
windows::core::w!("ZeroTick Device Monitor"),
WINDOW_STYLE(0),
0,
0,
0,
0,
Some(HWND_MESSAGE),
None,
Some(hinstance.into()),
None,
)?;
register_device_notification(hwnd, DEVINTERFACE_USB_DEVICE)?;
register_device_notification(hwnd, DEVINTERFACE_BLUETOOTH)?;
logging::info("硬件断连监控已启动(USB + 蓝牙 GUID 已注册)");
let mut msg = std::mem::zeroed();
while GetMessageW(&mut msg, None, 0, 0).as_bool() {
let _ = TranslateMessage(&msg);
DispatchMessageW(&msg);
}
UnregisterClassW(CLASS_NAME, Some(hinstance.into()))?;
}
Ok(())
}
unsafe fn register_device_notification(
hwnd: HWND,
class_guid: windows::core::GUID,
) -> windows::core::Result<()> {
let filter = DEV_BROADCAST_DEVICEINTERFACE_W {
dbcc_size: size_of::<DEV_BROADCAST_DEVICEINTERFACE_W>() as u32,
dbcc_devicetype: DBT_DEVTYP_DEVICEINTERFACE.0,
dbcc_classguid: class_guid,
..Default::default()
};
let _ = RegisterDeviceNotificationW(
HANDLE(hwnd.0),
std::ptr::from_ref(&filter).cast(),
DEVICE_NOTIFY_WINDOW_HANDLE,
)?;
Ok(())
}
unsafe extern "system" fn device_wnd_proc(
hwnd: HWND,
msg: u32,
wparam: WPARAM,
lparam: LPARAM,
) -> LRESULT {
match msg {
WM_DEVICECHANGE => {
handle_device_change(wparam, lparam);
LRESULT(0)
}
WM_DESTROY => {
PostQuitMessage(0);
LRESULT(0)
}
_ => DefWindowProcW(hwnd, msg, wparam, lparam),
}
}
unsafe fn handle_device_change(wparam: WPARAM, lparam: LPARAM) {
let event = wparam.0 as u32;
if event != DBT_DEVICEARRIVAL && event != DBT_DEVICEREMOVECOMPLETE {
return;
}
if lparam.0 == 0 {
return;
}
let hdr = &*(lparam.0 as *const DEV_BROADCAST_HDR);
if hdr.dbch_devicetype != DBT_DEVTYP_DEVICEINTERFACE {
return;
}
let iface = &*(lparam.0 as *const DEV_BROADCAST_DEVICEINTERFACE_W);
let path = read_device_interface_path(iface);
if path.is_empty() {
return;
}
let (category, vid_pid) = parse_device_path(&path);
let tracker = match TRACKER.get() {
Some(t) => t,
None => return,
};
match event {
DBT_DEVICEARRIVAL => {
let mut guard = match tracker.lock() {
Ok(g) => g,
Err(_) => return,
};
if let Some(elapsed) = guard.record_arrival(&path) {
let ms = elapsed.as_millis() as u64;
let threshold = Duration::from_millis(settings::get().transient_threshold_ms);
if is_transient_disconnect(elapsed, threshold) {
logging::critical(format!("[瞬断] {path} — {ms}ms"));
push_event(
"transient_reconnect",
category,
vid_pid,
path,
Some(ms),
TrayLevel::Critical,
"transient_hw",
);
} else {
logging::warn(format!("Reconnect {path} — {ms}ms"));
push_event(
"arrival",
category,
vid_pid,
path,
Some(ms),
TrayLevel::Warning,
"device_reconnect",
);
}
} else {
logging::info(format!("Arrival {path}"));
push_event(
"arrival",
category,
vid_pid,
path,
None,
TrayLevel::Normal,
"device_arrival",
);
}
}
DBT_DEVICEREMOVECOMPLETE => {
let mut guard = match tracker.lock() {
Ok(g) => g,
Err(_) => return,
};
guard.record_disconnect(&path);
logging::warn(format!("Remove {path}"));
push_event(
"remove",
category,
vid_pid,
path,
None,
TrayLevel::Warning,
"device_remove",
);
}
_ => {}
}
}
unsafe fn read_device_interface_path(iface: &DEV_BROADCAST_DEVICEINTERFACE_W) -> String {
use windows::core::PCWSTR;
PCWSTR(iface.dbcc_name.as_ptr())
.to_string()
.unwrap_or_default()
}