-
Notifications
You must be signed in to change notification settings - Fork 0
/
serial.go
66 lines (50 loc) · 927 Bytes
/
serial.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
package main
import (
"fmt"
"github.com/tarm/serial"
)
func OpenPort() (*serial.Port, error) {
cfg := &serial.Config{
Name: "/dev/ttyUSB0",
Baud: 115200,
Size: 8,
StopBits: 1,
}
port, err := serial.OpenPort(cfg)
if err != nil {
return nil, err
}
return port, nil
}
func ReadLoop(port *serial.Port, meterChan chan *MeterData) {
buf := make([]byte, 1024)
var data *MeterData
for {
bits, err := port.Read(buf)
if err != nil {
fmt.Println(err)
continue
}
if bits == 0 {
//should not happen in blocking mode
continue
}
//a new data block always begins with /
if buf[0] == '/' {
data = new(MeterData)
}
if data == nil {
//discard any data if we are not "within" a data block
continue
}
complete, err := data.Append(buf[:bits])
if err != nil {
fmt.Println(err)
continue
}
if complete {
meterChan <- data
data = nil
}
}
}