-
Notifications
You must be signed in to change notification settings - Fork 0
/
parse.go
108 lines (92 loc) · 2.15 KB
/
parse.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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
package main
// Current Cost CC128 Real-Time power usage exported as Prometheus metrics.
// Reads serial port data as per http://www.currentcost.com/cc128/xml.htm
import (
"bufio"
"encoding/xml"
"flag"
"fmt"
"time"
"github.com/prometheus/common/log"
"github.com/tarm/serial"
"golang.org/x/net/trace"
)
var (
serialDev = flag.String("dev", "/dev/ttyUSB0", "serial port")
baudRate = flag.Int("baud", 57600, "serial port baud rate")
)
type wattUsage struct {
// use strings so setGauge() can check for presence vs zero
XMLName xml.Name `xml:"msg"`
TempC string `xml:"tmpr"`
TempF string `xml:"tmprF"`
Watts1 string `xml:"ch1>watts"`
Watts2 string `xml:"ch2>watts"`
}
// not exactly idiomatic go
func updateMetrics(tr trace.Trace, w *wattUsage) {
e := func(err error) {
if err != nil {
parseErrors.Inc()
tr.LazyPrintf("%v", err)
tr.SetError()
}
}
e(setGauge(tempC, w.TempC))
e(setGauge(tempF, w.TempF))
e(setGauge(watts.WithLabelValues("ch1"), w.Watts1))
e(setGauge(watts.WithLabelValues("ch2"), w.Watts2))
}
// NOTE: be careful to not retain references to 'd' buffer
// (consider changing this to take a string)
func parseWattLine(d []byte) {
tr := trace.New("parseWattLine", "xml")
defer tr.Finish()
tr.LazyPrintf(fmt.Sprintf("input: %s", d)) // don't leak 'd'.
w := new(wattUsage)
err := xml.Unmarshal(d, &w)
if err != nil {
parseErrors.Inc()
log.Errorf("xml: %v", err)
tr.LazyPrintf("xml: %v", err)
tr.SetError()
return
}
tr.LazyPrintf("%+v", w)
updateMetrics(tr, w)
}
func readWattLine(d []byte) {
// ignore blank lines
if len(d) == 0 {
return
}
readCount.Inc()
readTime.Set(float64(time.Now().Unix()))
parseWattLine(d)
}
func readInput() {
tr := trace.NewEventLog("readInput", *serialDev)
defer tr.Finish()
f, err := serial.OpenPort(
&serial.Config{
Name: *serialDev,
Baud: *baudRate,
})
if err != nil {
readErrors.Inc()
tr.Errorf("open: %v", err)
log.Error(err)
return
}
defer f.Close()
s := bufio.NewScanner(f)
for s.Scan() {
readWattLine(s.Bytes())
}
err = s.Err()
if err != nil {
readErrors.Inc()
tr.Errorf("scanner: %v", err)
log.Errorf("scanner: %v", err)
}
}