-
Notifications
You must be signed in to change notification settings - Fork 0
/
reader.go
73 lines (58 loc) · 1.38 KB
/
reader.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
package main
import (
"errors"
"fmt"
"github.com/devfacet/gocmd"
"github.com/goburrow/modbus"
"time"
)
func readData(port string, address byte, formatter Formatter, interval time.Duration) {
handler := getHandler(port, address)
defer closePort(handler)
_ = handler.Connect()
client := modbus.NewClient(handler)
for {
start := time.Now()
data, err := readSingleMeasurement(client)
if err != nil {
fmt.Println(err.Error())
continue
}
data.Address = address
fmt.Print(formatter.format(data))
sleep := interval - time.Now().Sub(start)
if sleep < 0 {
sleep = 0
}
time.Sleep(sleep)
}
}
func readSingleMeasurement(client modbus.Client) (data Pzem017data, err error) {
results, err := client.ReadInputRegisters(0, 8)
if err != nil {
return Pzem017data{}, err
}
data = CreatePzem017FromBytes(results)
if data.validate() == false {
return Pzem017data{}, errors.New("Invalid data")
}
return data, nil
}
func registerCommandRead(flags *Commands) {
_, _ = gocmd.HandleFlag("Read", func(cmd *gocmd.Cmd, args []string) error {
format := flags.Read.Format
if format == "" {
format = "txt"
}
formatter, err := getFormatFactory().getByName(format)
if err != nil {
fmt.Println(err.Error())
return nil
}
readData(
flags.Read.Port,
byte(flags.Read.Address),
formatter, time.Duration(flags.Read.Interval)*time.Millisecond)
return nil
})
}