50 lines
941 B
Go
50 lines
941 B
Go
package serial
|
|||
|
|
|
||
|
|
import (
|
||
|
|
"time"
|
||
|
|
|
||
|
|
"github.com/argandas/serial"
|
||
|
|
)
|
||
|
|
|
||
|
|
// Reader defines the interface for serial port operations.
|
||
|
|
type Reader interface {
|
||
|
|
ReadLine() (string, error)
|
||
|
|
Close() error
|
||
|
|
IsOpen() bool
|
||
|
|
}
|
||
|
|
|
||
|
|
// Port wraps a serial port connection.
|
||
|
|
type Port struct {
|
||
|
|
sp *serial.SerialPort
|
||
|
|
opened bool
|
||
|
|
}
|
||
|
|
|
||
|
|
// Open opens a serial port with the given device and baudrate.
|
||
|
|
func Open(device string, baudrate int) (*Port, error) {
|
||
|
|
sp := serial.New()
|
||
|
|
sp.EOL('\r')
|
||
|
|
sp.Verbose = false
|
||
|
|
|
||
|
|
err := sp.Open(device, baudrate, 3*time.Second)
|
||
|
|
if err != nil {
|
||
|
|
return nil, err
|
||
|
|
}
|
||
|
|
|
||
|
|
return &Port{sp: sp, opened: true}, nil
|
||
|
|
}
|
||
|
|
|
||
|
|
// ReadLine reads one line from the serial port.
|
||
|
|
func (p *Port) ReadLine() (string, error) {
|
||
|
|
return p.sp.ReadLine()
|
||
|
|
}
|
||
|
|
|
||
|
|
// Close closes the serial port.
|
||
|
|
func (p *Port) Close() error {
|
||
|
|
p.opened = false
|
||
|
|
return nil
|
||
|
|
}
|
||
|
|
|
||
|
|
// IsOpen returns whether the port is currently open.
|
||
|
|
func (p *Port) IsOpen() bool {
|
||
|
|
return p.opened
|
||
|
|
}
|