Browse Source

移除多线程读取,只执行一次函数

caner 1 year ago
parent
commit
ccf1bc1b37
5 changed files with 35 additions and 67 deletions
  1. 7 46
      src-tauri/src/lib.rs
  2. 14 2
      src/App.vue
  3. 10 0
      src/components/notifaiction.vue
  4. 1 19
      src/pages/room/component/steering.vue
  5. 3 0
      src/vite-env.d.ts

+ 7 - 46
src-tauri/src/lib.rs

@@ -1,13 +1,6 @@
-use std::sync::{Arc, Mutex, atomic::{AtomicBool, Ordering}};
 use std::thread;
 use std::thread;
 use hidapi::HidApi;
 use hidapi::HidApi;
 use tauri::{Emitter,Window};
 use tauri::{Emitter,Window};
-// 全局停止标志和线程句柄
-lazy_static::lazy_static! {
-    static ref STOP_SIGNAL: AtomicBool = AtomicBool::new(false);
-    static ref THREAD_HANDLE: Mutex<Option<thread::JoinHandle<()>>> = Mutex::new(None);
-}
-// G923设备标识
 const LOGITECH_VID: u16 = 0x046D;  // 罗技厂商ID
 const LOGITECH_VID: u16 = 0x046D;  // 罗技厂商ID
 const G923_PIDS: &[u16] = &[
 const G923_PIDS: &[u16] = &[
     0xC262,  // G923 PlayStation
     0xC262,  // G923 PlayStation
@@ -18,10 +11,8 @@ const G923_PIDS: &[u16] = &[
 // 读取G923数据
 // 读取G923数据
 #[tauri::command]
 #[tauri::command]
 fn start_reading_data(window: Window) -> Result<(), String> {
 fn start_reading_data(window: Window) -> Result<(), String> {
-    // 停止现有线程
-    stop_reading_data();
     // 初始化HID API
     // 初始化HID API
-    let api = HidApi::new().map_err(|_| "HID初始化失败".to_string())?;
+    let api = HidApi::new().map_err(|_| "HID设备初始化失败".to_string())?;
     // 自动检测设备
     // 自动检测设备
     let device_info = api.device_list().find(|d| d.vendor_id() == LOGITECH_VID && G923_PIDS.contains(&d.product_id())).ok_or("未找到G923方向盘")?;
     let device_info = api.device_list().find(|d| d.vendor_id() == LOGITECH_VID && G923_PIDS.contains(&d.product_id())).ok_or("未找到G923方向盘")?;
     // 打印检测到的设备信息
     // 打印检测到的设备信息
@@ -30,63 +21,33 @@ fn start_reading_data(window: Window) -> Result<(), String> {
         device_info.product_id());
         device_info.product_id());
     // 打开设备
     // 打开设备
     let device = device_info.open_device(&api).map_err(|e| format!("无法打开设备: {}", e))?;
     let device = device_info.open_device(&api).map_err(|e| format!("无法打开设备: {}", e))?;
-    // 发送初始化命令
-    // let init_report = [0x02u8, 0x00, 0x00, 0x00, 0x00]; // 根据实际协议调整
-    // device.send_feature_report(&init_report).map_err(|e| format!("设备初始化失败: {}", e))?;
-    // 设置非阻塞模式(可选)
-    device.set_blocking_mode(false).map_err(|e| format!("设置非阻塞模式失败: {}", e))?;
-    // 克隆Arc用于线程
-    let device = Arc::new(Mutex::new(device));
-    let thread_device = Arc::clone(&device);
-    let thread_window = window.clone();
     // 启动读取线程
     // 启动读取线程
-    let handle = thread::spawn(move || {
+    thread::spawn(move || {
         let mut buf = [0u8; 64];
         let mut buf = [0u8; 64];
         loop {
         loop {
-            // 检查停止标志
-            if STOP_SIGNAL.load(Ordering::SeqCst) {
-                println!("停止读取线程");
-                break;
-            }
-
             // 使用带超时的读取(100ms)
             // 使用带超时的读取(100ms)
-            let res = match thread_device.lock().unwrap().read_timeout(&mut buf, 100) {
+            let res = match device.read_timeout(&mut buf, 100) {
                 Ok(n) => n,
                 Ok(n) => n,
                 Err(e) => {
                 Err(e) => {
                     eprintln!("读取数据失败: {}", e);
                     eprintln!("读取数据失败: {}", e);
-                    continue;
+                    break;
                 }
                 }
             };
             };
 
 
             // 处理&发送数据
             // 处理&发送数据
             let data = &buf[..res];
             let data = &buf[..res];
-            let _ = thread_window.emit("g923-data", format!("{:?}", data));
+            let _ = window.emit("g923-data", format!("{:?}", data));
         }
         }
-
-        // 关闭设备
-        drop(thread_device.lock().unwrap());
     });
     });
-    // 存储线程句柄
-    *THREAD_HANDLE.lock().unwrap() = Some(handle);
-    // return
-    Ok(())
-}
 
 
-// 设置停止
-#[tauri::command]
-fn stop_reading_data() {
-    STOP_SIGNAL.store(true, Ordering::SeqCst);
-    if let Some(handle) = THREAD_HANDLE.lock().unwrap().take() {
-       let _ = handle.join().map_err(|_| "无法等待线程退出".to_string());
-    }
-    STOP_SIGNAL.store(false, Ordering::SeqCst);
+    Ok(())
 }
 }
 
 
 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,stop_reading_data])
+        .invoke_handler(tauri::generate_handler![start_reading_data])
         .run(tauri::generate_context!())
         .run(tauri::generate_context!())
         .expect("error while running tauri application");
         .expect("error while running tauri application");
 }
 }

+ 14 - 2
src/App.vue

@@ -9,16 +9,20 @@
   >
   >
     <n-notification-provider>
     <n-notification-provider>
       <router-view />
       <router-view />
+      <global-notif />
     </n-notification-provider>
     </n-notification-provider>
   </n-config-provider>
   </n-config-provider>
 </template>
 </template>
 <script setup lang='ts'>
 <script setup lang='ts'>
 import { computed, provide, watch } from 'vue'
 import { computed, provide, watch } from 'vue'
+import { listen } from '@tauri-apps/api/event'
+import { invoke } from '@tauri-apps/api/core'
 import { zhCN, dateZhCN } from 'naive-ui'
 import { zhCN, dateZhCN } from 'naive-ui'
 import { useRouter } from 'vue-router'
 import { useRouter } from 'vue-router'
-import MqttService from '@/services/mqtt.service'
-import loading from '@/components/loading.vue'
 import Theme from '@/assets/naive-theme'
 import Theme from '@/assets/naive-theme'
+import loading from '@/components/loading.vue'
+import MqttService from '@/services/mqtt.service'
+import GlobalNotif from '@/components/notifaiction.vue'
 import useStore from './store/index'
 import useStore from './store/index'
 
 
 const mqtt = new MqttService()
 const mqtt = new MqttService()
@@ -27,6 +31,14 @@ const router = useRouter()
 const themeOverrides = Theme
 const themeOverrides = Theme
 const show = computed(() => store.loading)
 const show = computed(() => store.loading)
 
 
+invoke('start_reading_data').then(() => {
+  listen('g923-data', (event) => {
+    console.log('解析后的 G923 数据:', event)
+  })
+}).catch((er) => {
+  window.$notification.error({ title: er, duration: 3000 })
+})
+
 watch(() => store.mqtt_message, (val) => {
 watch(() => store.mqtt_message, (val) => {
   if (val.type === 'MqttConnect') {
   if (val.type === 'MqttConnect') {
     store.setLoading(true)
     store.setLoading(true)

+ 10 - 0
src/components/notifaiction.vue

@@ -0,0 +1,10 @@
+<template>
+  <div />
+</template>
+
+<script setup lang="ts">
+import { useNotification } from 'naive-ui'
+
+window.$notification = useNotification()
+
+</script>

+ 1 - 19
src/pages/room/component/steering.vue

@@ -7,15 +7,11 @@
   />
   />
 </template>
 </template>
 <script setup lang="ts">
 <script setup lang="ts">
-import { useNotification } from 'naive-ui'
-import { invoke } from '@tauri-apps/api/core'
-import { listen } from '@tauri-apps/api/event'
-import { computed, onUnmounted, ref } from 'vue'
+import { computed, 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 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,18 +31,4 @@ function parseG923Data(data) {
   }
   }
 }
 }
 
 
-invoke('start_reading_data').then(() => {
-  listen('g923-data', (event) => {
-    const data = event.payload
-    const parsedData = parseG923Data(data)
-    console.log('解析后的 G923 数据:', event, parsedData)
-  })
-}).catch((er) => {
-  show.value = false
-  console.log('output->', er)
-  notice.error({ title: er, duration: 3000 })
-})
-
-onUnmounted(() => { invoke('stop_reading_data') })
-
 </script>
 </script>

+ 3 - 0
src/vite-env.d.ts

@@ -8,4 +8,7 @@ declare module '*.vue' {
   import type { DefineComponent } from 'vue'
   import type { DefineComponent } from 'vue'
   const component: DefineComponent<{}, {}, Any>
   const component: DefineComponent<{}, {}, Any>
   export default component
   export default component
+}
+interface Window {
+  $notification: any
 }
 }