You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

74 lines
1.5 KiB
Go

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

package main
import (
"fmt"
"log"
"time"
"github.com/StackExchange/wmi"
"github.com/go-vgo/robotgo"
"github.com/tarm/serial"
)
type Win32_PnPEntity struct {
Name string
}
func check() string {
var devices []Win32_PnPEntity
query := `SELECT Name FROM Win32_PnPEntity WHERE Name LIKE '%(COM%'`
err := wmi.Query(query, &devices)
if err != nil {
panic(fmt.Sprintf("Failed to query WMI: %v", err))
}
return devices[0].Name[40:44]
}
func main() {
// 串口配置
com := check()
config := &serial.Config{
Name: com, // 替换为实际的串口设备路径例如在Windows上可能是"COM1"
Baud: 115200, // 波特率,根据实际需求设置
}
// 打开串口
port, err := serial.OpenPort(config)
if err != nil {
log.Fatal(err)
}
defer port.Close()
buffer := make([]byte, 128) // 缓冲区大小根据你的数据包大小调整
for {
n, err := port.Read(buffer)
if err != nil {
log.Printf("读取错误: %v\n", err)
continue
}
if n > 0 {
// 这里可以添加处理数据的逻辑
if buffer[0] == 0x01 {
robotgo.KeyPress("up")
} else if buffer[0] == 0x02 {
robotgo.KeyPress("down")
} else if buffer[0] == 0x10 {
robotgo.KeyPress("f")
} else {
log.Printf("读取到 %d 字节数据: %d\n", n, buffer[:n])
}
} else {
// 当没有读取到数据时,可以根据需要处理或简单跳过
log.Println("没有新数据")
}
// 可以根据需要添加适当的延迟避免无数据时CPU占用过高
time.Sleep(10 * time.Millisecond)
}
}