|
|
package main
|
|
|
|
|
|
import (
|
|
|
"fmt"
|
|
|
"log"
|
|
|
"regexp"
|
|
|
"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))
|
|
|
}
|
|
|
|
|
|
re := regexp.MustCompile(`COM\d+`)
|
|
|
dev := re.FindString(devices[0].Name)
|
|
|
return dev //获取串口名字
|
|
|
}
|
|
|
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] == 0x04 {
|
|
|
robotgo.KeyPress("z")
|
|
|
} 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)
|
|
|
}
|
|
|
}
|