DPF/serialport.go

77 lines
1.2 KiB
Go
Raw Normal View History

2019-11-01 13:47:11 +00:00
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"
2019-11-03 18:00:35 +00:00
sp.port1 = "/dev/pts/3"
sp.port2 = "/dev/pts/4"
2019-11-01 13:47:11 +00:00
2019-11-04 06:29:08 +00:00
// sp.port = "/dev/pts/3"
2019-11-01 13:47:11 +00:00
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 {
2019-11-03 18:00:35 +00:00
panic(err)
2019-11-01 13:47:11 +00:00
}
2019-11-03 18:00:35 +00:00
sp.linuxRPort = port1
2019-11-01 13:47:11 +00:00
cfg2 := &serial.Config{Name: sp.port2, Baud: sp.baud, ReadTimeout: 5}
port2, err := serial.OpenPort(cfg2)
if err != nil {
2019-11-03 18:00:35 +00:00
panic(err)
2019-11-01 13:47:11 +00:00
}
2019-11-03 18:00:35 +00:00
sp.linuxWPort = port2
2019-11-01 13:47:11 +00:00
} else {
cfg1 := &serial.Config{Name: sp.com, Baud: sp.baud, ReadTimeout: 5}
port1, err := serial.OpenPort(cfg1)
if err != nil {
2019-11-03 18:00:35 +00:00
panic(err)
2019-11-01 13:47:11 +00:00
}
2019-11-03 18:00:35 +00:00
sp.windowsRWPort = port1
2019-11-01 13:47:11 +00:00
}
}