-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathconnect.go
87 lines (79 loc) · 1.63 KB
/
connect.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
package main
import (
"bufio"
"fmt"
"io"
"time"
"github.com/pkg/term"
)
type Connect struct {
portPath string
baudRate int
port *term.Term
portReader *bufio.Reader
stateChan chan error
}
// NewConnection returns a pointer to a Connect instance
func NewConnection(portPath string, baudRate int) (*Connect, error) {
t := term.Speed(baudRate)
port, err := term.Open(portPath, t)
if err != nil {
return nil, err
}
port.SetRaw()
portReader := bufio.NewReader(port)
stateChan := make(chan error)
return &Connect{portPath: portPath, baudRate: baudRate, port: port,
portReader: portReader,
stateChan: stateChan}, nil
}
// Start initializes a read loop that attempts to reconnect
// when the connection is broken
func (c *Connect) Start() {
go c.read()
for {
select {
case err := <-c.stateChan:
if err != nil {
fmt.Printf("Error connecting to %s", c.portPath)
go c.initialize()
} else {
fmt.Printf(" | Connection to %s reestablished!", c.portPath)
go c.read()
}
}
}
}
func (c *Connect) initialize() {
c.port.Close()
for {
time.Sleep(time.Second)
port, err := term.Open(c.portPath)
if err != nil {
continue
}
c.port = port
c.portReader = bufio.NewReader(port)
c.stateChan <- nil
return
}
}
func (c *Connect) read() {
for {
response, err := c.portReader.ReadBytes('\n')
// report the error
if err != nil && err != io.EOF {
c.stateChan <- err
return
}
if len(response) > 0 {
fmt.Print(string(response))
}
}
}
func (c *Connect) Write(message []byte) {
_, err := c.port.Write(message)
if err != nil {
fmt.Printf("Error writing to serial port: %v ", err)
}
}