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.

69 lines
1.4 KiB
Go

7 months ago
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 {
7 months ago
7 months ago
// 这里可以添加处理数据的逻辑
if buffer[0] == 0x02 {
robotgo.Click("left")
7 months ago
} else {
log.Printf("读取到 %d 字节数据: %d\n", n, buffer[:n])
7 months ago
}
} else {
// 当没有读取到数据时,可以根据需要处理或简单跳过
7 months ago
log.Println("没有新数据")
7 months ago
}
// 可以根据需要添加适当的延迟避免无数据时CPU占用过高
time.Sleep(10 * time.Millisecond)
}
}