77 lines
1.2 KiB
Go
77 lines
1.2 KiB
Go
package main
|
|
|
|
import (
|
|
"io"
|
|
"sync"
|
|
|
|
serial "github.com/tarm/goserial"
|
|
)
|
|
|
|
// CurrentOS 系统类别
|
|
const CurrentOS = "linux"
|
|
|
|
// SerialPort 串口
|
|
type SerialPort struct {
|
|
com string
|
|
port1 string
|
|
port2 string
|
|
|
|
windowsRWLock *sync.Mutex
|
|
windowsRWPort io.ReadWriteCloser
|
|
|
|
linuxRPort io.ReadWriteCloser
|
|
linuxWPort io.ReadWriteCloser
|
|
|
|
baud int // 9600
|
|
}
|
|
|
|
// NewSerialPort 创建串口
|
|
func NewSerialPort() *SerialPort {
|
|
|
|
sp := &SerialPort{}
|
|
|
|
sp.com = "COM1"
|
|
|
|
sp.port1 = "/dev/pts/3"
|
|
sp.port2 = "/dev/pts/4"
|
|
|
|
// sp.port = "/dev/pts/3"
|
|
|
|
sp.baud = 9600
|
|
|
|
sp.windowsRWLock = &sync.Mutex{}
|
|
|
|
return sp
|
|
}
|
|
|
|
// OpenPort 打开串口
|
|
func (sp *SerialPort) OpenPort() {
|
|
|
|
if CurrentOS == "linux" {
|
|
|
|
cfg1 := &serial.Config{Name: sp.port1, Baud: sp.baud, ReadTimeout: 5}
|
|
port1, err := serial.OpenPort(cfg1)
|
|
if err != nil {
|
|
panic(err)
|
|
}
|
|
sp.linuxRPort = port1
|
|
|
|
cfg2 := &serial.Config{Name: sp.port2, Baud: sp.baud, ReadTimeout: 5}
|
|
port2, err := serial.OpenPort(cfg2)
|
|
if err != nil {
|
|
panic(err)
|
|
}
|
|
sp.linuxWPort = port2
|
|
|
|
} else {
|
|
|
|
cfg1 := &serial.Config{Name: sp.com, Baud: sp.baud, ReadTimeout: 5}
|
|
port1, err := serial.OpenPort(cfg1)
|
|
if err != nil {
|
|
panic(err)
|
|
}
|
|
sp.windowsRWPort = port1
|
|
}
|
|
|
|
}
|