lib.rs 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. use std::sync::{Arc, Mutex, atomic::{AtomicBool, Ordering}};
  2. use std::thread;
  3. use std::time::Duration;
  4. use hidapi::HidApi;
  5. use tauri::{Emitter,Window};
  6. static STOP_SIGNAL: AtomicBool = AtomicBool::new(false);
  7. // 读取G923数据
  8. #[tauri::command]
  9. fn start_reading_data(window: Window) -> Result<(), String> {
  10. // 重置标志位
  11. STOP_SIGNAL.store(false, Ordering::SeqCst);
  12. // 初始化 HidApi
  13. let api_result = HidApi::new();
  14. if let Err(_e) = api_result {
  15. return Err("HID设备初始化失败".to_string());
  16. }
  17. let api = Arc::new(Mutex::new(api_result.unwrap()));
  18. // 打开 G923 设备
  19. let device_result = api.lock().unwrap().open(0x046D, 0xC267);
  20. if let Err(_e) = device_result {
  21. return Err("请连接-G923-方向盘".to_string());
  22. }
  23. let device = Arc::new(Mutex::new(device_result.unwrap()));
  24. // 启动一个线程持续读取数据
  25. thread::spawn(move || {
  26. let mut buf = [0u8; 64]; // HID 设备通常使用 64 字节的缓冲区
  27. loop {
  28. // 检查标志位,如果为 true,则退出线程
  29. if STOP_SIGNAL.load(Ordering::SeqCst) {
  30. println!("线程已退出并关闭设备");
  31. drop(device.lock().unwrap());
  32. break;
  33. }
  34. let res = match device.lock().unwrap().read(&mut buf) {
  35. Ok(res) => res,
  36. Err(e) => {
  37. eprintln!("读取数据失败: {}", e);
  38. continue;
  39. }
  40. };
  41. let data = &buf[..res];
  42. // 将数据发送到前端
  43. if let Err(e) = window.emit("g923-data", format!("{:?}", data)) {
  44. eprintln!("发送数据到前端失败: {}", e);
  45. }
  46. // 休眠一段时间(例如 10ms)
  47. thread::sleep(Duration::from_millis(10));
  48. }
  49. });
  50. Ok(())
  51. }
  52. // 设置停止
  53. #[tauri::command]
  54. fn stop_reading_data() {
  55. STOP_SIGNAL.store(true, Ordering::SeqCst);
  56. }
  57. pub fn run() {
  58. tauri::Builder::default()
  59. .plugin(tauri_plugin_shell::init())
  60. .plugin(tauri_plugin_mqtt::init())
  61. .invoke_handler(tauri::generate_handler![start_reading_data,stop_reading_data])
  62. .run(tauri::generate_context!())
  63. .expect("error while running tauri application");
  64. }