DPF/serialport.go
huangsimin 5515ece4f0 init
2019-11-01 21:47:11 +08:00

73 lines
1.1 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/11"
sp.port2 = "/dev/pts/12"
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 {
sp.linuxRPort = port1
}
cfg2 := &serial.Config{Name: sp.port2, Baud: sp.baud, ReadTimeout: 5}
port2, err := serial.OpenPort(cfg2)
if err != nil {
sp.linuxWPort = port2
}
} else {
cfg1 := &serial.Config{Name: sp.com, Baud: sp.baud, ReadTimeout: 5}
port1, err := serial.OpenPort(cfg1)
if err != nil {
sp.windowsRWPort = port1
}
}
}