Browse Source

测试读取方向盘数据

Caner 1 year ago
parent
commit
ecf8bfd7a5
6 changed files with 68 additions and 31 deletions
  1. 2 1
      .eslintrc.json
  2. 13 0
      src-tauri/Cargo.lock
  3. 1 0
      src-tauri/Cargo.toml
  4. 27 1
      src-tauri/src/lib.rs
  5. 21 27
      src/components/steering.vue
  6. 4 2
      src/pages/room/index.vue

+ 2 - 1
.eslintrc.json

@@ -57,6 +57,7 @@
     "class-methods-use-this": 0,
     "no-return-await": 0,
     "no-throw-literal": 0,
-    "no-undef": 0
+    "no-undef": 0,
+    "no-bitwise": 0
   }
 }

+ 13 - 0
src-tauri/Cargo.lock

@@ -6,6 +6,7 @@ version = 4
 name = "Control"
 version = "0.1.0"
 dependencies = [
+ "hidapi",
  "serde",
  "serde_json",
  "tauri",
@@ -1301,6 +1302,18 @@ version = "0.4.3"
 source = "registry+https://github.com/rust-lang/crates.io-index"
 checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70"
 
+[[package]]
+name = "hidapi"
+version = "1.5.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "798154e4b6570af74899d71155fb0072d5b17e6aa12f39c8ef22c60fb8ec99e7"
+dependencies = [
+ "cc",
+ "libc",
+ "pkg-config",
+ "winapi",
+]
+
 [[package]]
 name = "html5ever"
 version = "0.26.0"

+ 1 - 0
src-tauri/Cargo.toml

@@ -23,3 +23,4 @@ serde = { version = "1", features = ["derive"] }
 serde_json = "1"
 tauri-plugin-mqtt = "0.1.1"
 tauri-plugin-shell = "2"
+hidapi = "1.3"

+ 27 - 1
src-tauri/src/lib.rs

@@ -1,9 +1,35 @@
+use hidapi::HidApi;
+use std::sync::{Arc, Mutex};
+use std::thread;
+use std::time::Duration;
+use tauri::{Emitter,Window};
+
+#[tauri::command]
+fn start_reading_data(window: Window) {
+    // 初始化 HidApi
+    let api = Arc::new(Mutex::new(HidApi::new().expect("无法初始化 HidApi")));
+    // 打开 G923 设备
+    let device = api.lock().unwrap().open(0x046D, 0xC267).expect("设备打开失败");
+    // 启动一个线程持续读取数据
+    thread::spawn(move || {
+        let mut buf = [0u8; 64]; // HID 设备通常使用 64 字节的缓冲区
+        loop {
+            let res = device.read(&mut buf).expect("读取数据失败");
+            let data = &buf[..res];
+
+            // 将数据发送到前端
+            window.emit("g923-data", format!("{:?}", data)).unwrap();
+            // 休眠一段时间(例如 10ms)
+            thread::sleep(Duration::from_millis(10));
+        }
+    });
+}
 
 pub fn run() {
     tauri::Builder::default()
         .plugin(tauri_plugin_shell::init())
         .plugin(tauri_plugin_mqtt::init())
-        .invoke_handler(tauri::generate_handler![])
+        .invoke_handler(tauri::generate_handler![start_reading_data])
         .run(tauri::generate_context!())
         .expect("error while running tauri application");
 }

+ 21 - 27
src/components/steering.vue

@@ -7,7 +7,9 @@
   />
 </template>
 <script setup lang="ts">
-import { computed, onUnmounted, ref } from 'vue'
+import { invoke } from '@tauri-apps/api/core'
+import { listen } from '@tauri-apps/api/event'
+import { computed, ref } from 'vue'
 import { useMessage } from 'naive-ui'
 import useStore from '@/store'
 
@@ -17,35 +19,27 @@ const store = useStore()
 const rtcConnected = computed(() => store.rtcConnected)
 const show = ref(false)
 
-// 更新游戏手柄数据
-function updateGamepadData() {
-  const gamepads = navigator.getGamepads()
-  const gamepad = gamepads[0] // 获取第一个连接的游戏手柄
-  if (gamepad) {
-    // 显示游戏手柄数据
-    emit('callBack', gamepad)
+function parseG923Data(data) {
+  // 假设数据是一个数组,例如 [128, 255, 0, 0, ...]
+  const buffer = new Uint8Array(data)
+
+  // 解析转向值(假设存储在 buffer[0] 和 buffer[1] 中,小端序)
+  const steeringValue = (buffer[1] << 8) | buffer[0]
+
+  // 解析刹车值(假设存储在 buffer[2] 中)
+  const brakeValue = buffer[2]
+
+  return {
+    steering: steeringValue,
+    brake: brakeValue
   }
-  // 循环更新数据
-  return requestAnimationFrame(updateGamepadData)
 }
 
-// 监听游戏手柄连接事件
-window.addEventListener('gamepadconnected', (event) => {
-  console.log('Gamepad connected:', event.gamepad)
-  show.value = true
-  updateGamepadData()
+invoke('start_reading_data')
+listen('g923-data', (event) => {
+  const data = event.payload
+  const parsedData = parseG923Data(data)
+  console.log('解析后的 G923 数据:', data, parsedData)
 })
 
-// 监听游戏手柄断开事件
-window.addEventListener('gamepaddisconnected', () => {
-  show.value = false
-  cancelAnimationFrame(updateGamepadData())
-  message.warning('控制器断开')
-})
-
-onUnmounted(() => {
-  cancelAnimationFrame(updateGamepadData())
-  window.removeEventListener('gamepadconnected', () => { show.value = false })
-  window.removeEventListener('gamepaddisconnected', () => { show.value = false })
-})
 </script>

+ 4 - 2
src/pages/room/index.vue

@@ -49,8 +49,10 @@ const menuList = shallowRef([
   {
     name: '方向盘',
     component: defineAsyncComponent(() => import('@/components/steering.vue')),
-    callBack: () => {
-      console.log('方向盘')
+    callBack: (gamepad) => {
+      const { axes, buttons } = gamepad
+      console.log('方向盘', axes)
+      console.log('方向盘按钮', buttons)
     }
   },
   {