45 lines
766 B
Go
45 lines
766 B
Go
package relay
|
|
|
|
import (
|
|
"bufio"
|
|
"fmt"
|
|
"go.bug.st/serial"
|
|
"io"
|
|
)
|
|
|
|
type Device struct {
|
|
port serial.Port
|
|
}
|
|
|
|
func (r *Device) Close() error {
|
|
return r.port.Close()
|
|
}
|
|
|
|
func (r *Device) On(num int) error {
|
|
_, err := io.WriteString(r.port, fmt.Sprintf("AT+OUT%v+1=ON\r\n", num))
|
|
return err
|
|
}
|
|
|
|
func (r *Device) Off(num int) error {
|
|
_, err := io.WriteString(r.port, fmt.Sprintf("AT+OUT%v+1=OFF\r\n", num))
|
|
return err
|
|
}
|
|
|
|
func New(portName string, reader func(msg string)) (*Device, error) {
|
|
port, err := serial.Open(portName, &serial.Mode{
|
|
BaudRate: 9600,
|
|
DataBits: 8,
|
|
})
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
go func() {
|
|
for {
|
|
r := bufio.NewReader(port)
|
|
line, _, _ := r.ReadLine()
|
|
reader(string(line))
|
|
}
|
|
}()
|
|
return &Device{port: port}, nil
|
|
}
|