Browse Source

接入罗技G923方向盘

caner 1 year ago
parent
commit
e8396322f7
4 changed files with 56 additions and 22 deletions
  1. 41 9
      src-tauri/src/lib.rs
  2. 1 3
      src/App.vue
  3. 0 2
      src/assets/native-plugin.ts
  4. 14 8
      src/components/steering.vue

+ 41 - 9
src-tauri/src/lib.rs

@@ -1,35 +1,67 @@
-use hidapi::HidApi;
-use std::sync::{Arc, Mutex};
+use std::sync::{Arc, Mutex, atomic::{AtomicBool, Ordering}};
 use std::thread;
 use std::thread;
 use std::time::Duration;
 use std::time::Duration;
+use hidapi::HidApi;
 use tauri::{Emitter,Window};
 use tauri::{Emitter,Window};
+static STOP_SIGNAL: AtomicBool = AtomicBool::new(false);
 
 
+// 读取G923数据
 #[tauri::command]
 #[tauri::command]
-fn start_reading_data(window: Window) {
+fn start_reading_data(window: Window) -> Result<(), String> {
+    // 重置标志位
+    STOP_SIGNAL.store(false, Ordering::SeqCst);
     // 初始化 HidApi
     // 初始化 HidApi
-    let api = Arc::new(Mutex::new(HidApi::new().expect("无法初始化 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 设备
     // 打开 G923 设备
-    let device = api.lock().unwrap().open(0x046D, 0xC267).expect("设备打开失败");
+    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 || {
     thread::spawn(move || {
         let mut buf = [0u8; 64]; // HID 设备通常使用 64 字节的缓冲区
         let mut buf = [0u8; 64]; // HID 设备通常使用 64 字节的缓冲区
         loop {
         loop {
-            let res = device.read(&mut buf).expect("读取数据失败");
+            // 检查标志位,如果为 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];
             let data = &buf[..res];
-
             // 将数据发送到前端
             // 将数据发送到前端
-            window.emit("g923-data", format!("{:?}", data)).unwrap();
+            if let Err(e) = window.emit("g923-data", format!("{:?}", data)) {
+                eprintln!("发送数据到前端失败: {}", e);
+            }
             // 休眠一段时间(例如 10ms)
             // 休眠一段时间(例如 10ms)
             thread::sleep(Duration::from_millis(10));
             thread::sleep(Duration::from_millis(10));
         }
         }
     });
     });
+    Ok(())
+}
+
+// 设置停止
+#[tauri::command]
+fn stop_reading_data() {
+    STOP_SIGNAL.store(true, Ordering::SeqCst);
 }
 }
 
 
 pub fn run() {
 pub fn run() {
     tauri::Builder::default()
     tauri::Builder::default()
         .plugin(tauri_plugin_shell::init())
         .plugin(tauri_plugin_shell::init())
         .plugin(tauri_plugin_mqtt::init())
         .plugin(tauri_plugin_mqtt::init())
-        .invoke_handler(tauri::generate_handler![start_reading_data])
+        .invoke_handler(tauri::generate_handler![start_reading_data,stop_reading_data])
         .run(tauri::generate_context!())
         .run(tauri::generate_context!())
         .expect("error while running tauri application");
         .expect("error while running tauri application");
 }
 }

+ 1 - 3
src/App.vue

@@ -8,9 +8,7 @@
     :date-locale="dateZhCN"
     :date-locale="dateZhCN"
   >
   >
     <n-notification-provider>
     <n-notification-provider>
-      <n-message-provider>
-        <router-view />
-      </n-message-provider>
+      <router-view />
     </n-notification-provider>
     </n-notification-provider>
   </n-config-provider>
   </n-config-provider>
 </template>
 </template>

+ 0 - 2
src/assets/native-plugin.ts

@@ -1,7 +1,6 @@
 import {
 import {
   create,
   create,
   NConfigProvider,
   NConfigProvider,
-  NMessageProvider,
   NNotificationProvider,
   NNotificationProvider,
   NButton
   NButton
 } from 'naive-ui'
 } from 'naive-ui'
@@ -9,7 +8,6 @@ import {
 const naive = create({
 const naive = create({
   components: [
   components: [
     NConfigProvider,
     NConfigProvider,
-    NMessageProvider,
     NNotificationProvider,
     NNotificationProvider,
     NButton
     NButton
   ]
   ]

+ 14 - 8
src/components/steering.vue

@@ -7,15 +7,15 @@
   />
   />
 </template>
 </template>
 <script setup lang="ts">
 <script setup lang="ts">
+import { useNotification } from 'naive-ui'
 import { invoke } from '@tauri-apps/api/core'
 import { invoke } from '@tauri-apps/api/core'
 import { listen } from '@tauri-apps/api/event'
 import { listen } from '@tauri-apps/api/event'
-import { computed, ref } from 'vue'
-import { useMessage } from 'naive-ui'
+import { computed, onUnmounted, ref } from 'vue'
 import useStore from '@/store'
 import useStore from '@/store'
 
 
 const emit = defineEmits<{(evt: 'callBack', value: Any): void }>()
 const emit = defineEmits<{(evt: 'callBack', value: Any): void }>()
-const message = useMessage()
 const store = useStore()
 const store = useStore()
+const notice = useNotification()
 const rtcConnected = computed(() => store.rtcConnected)
 const rtcConnected = computed(() => store.rtcConnected)
 const show = ref(false)
 const show = ref(false)
 
 
@@ -35,11 +35,17 @@ function parseG923Data(data) {
   }
   }
 }
 }
 
 
-invoke('start_reading_data')
-listen('g923-data', (event) => {
-  const data = event.payload
-  const parsedData = parseG923Data(data)
-  console.log('解析后的 G923 数据:', data, parsedData)
+invoke('start_reading_data').then(() => {
+  listen('g923-data', (event) => {
+    const data = event.payload
+    const parsedData = parseG923Data(data)
+    console.log('解析后的 G923 数据:', data, parsedData)
+  })
+}).catch((er) => {
+  show.value = false
+  notice.error({ title: er, duration: 3000 })
 })
 })
 
 
+onUnmounted(() => { invoke('stop_reading_data') })
+
 </script>
 </script>