use std::sync::{Arc, Mutex, atomic::{AtomicBool, Ordering}}; use std::thread; use std::time::Duration; use hidapi::HidApi; use tauri::{Emitter,Window}; static STOP_SIGNAL: AtomicBool = AtomicBool::new(false); // 读取G923数据 #[tauri::command] fn start_reading_data(window: Window) -> Result<(), String> { // 重置标志位 STOP_SIGNAL.store(false, Ordering::SeqCst); // 初始化 HidApi let api_result = HidApi::new(); if let Err(_e) = api_result { return Err("HID设备初始化失败".to_string()); } let api = Arc::new(Mutex::new(api_result.unwrap())); // 打开 G923 设备 let device_result = api.lock().unwrap().open(0x046D, 0xC267); if let Err(_e) = device_result { return Err("请连接-G923-方向盘".to_string()); } let device = Arc::new(Mutex::new(device_result.unwrap())); // 启动一个线程持续读取数据 thread::spawn(move || { let mut buf = [0u8; 64]; // HID 设备通常使用 64 字节的缓冲区 loop { // 检查标志位,如果为 true,则退出线程 if STOP_SIGNAL.load(Ordering::SeqCst) { println!("线程已退出并关闭设备"); drop(device.lock().unwrap()); break; } let res = match device.lock().unwrap().read(&mut buf) { Ok(res) => res, Err(e) => { eprintln!("读取数据失败: {}", e); continue; } }; let data = &buf[..res]; // 将数据发送到前端 if let Err(e) = window.emit("g923-data", format!("{:?}", data)) { eprintln!("发送数据到前端失败: {}", e); } // 休眠一段时间(例如 10ms) thread::sleep(Duration::from_millis(10)); } }); Ok(()) } // 设置停止 #[tauri::command] fn stop_reading_data() { STOP_SIGNAL.store(true, Ordering::SeqCst); } pub fn run() { tauri::Builder::default() .plugin(tauri_plugin_shell::init()) .plugin(tauri_plugin_mqtt::init()) .invoke_handler(tauri::generate_handler![start_reading_data,stop_reading_data]) .run(tauri::generate_context!()) .expect("error while running tauri application"); }