-
Notifications
You must be signed in to change notification settings - Fork 6
/
main.go
181 lines (154 loc) · 4.3 KB
/
main.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
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
package main
import (
"context"
"fmt"
"log"
"net/http"
"strings"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promhttp"
"gopkg.in/alecthomas/kingpin.v2"
)
var (
device = kingpin.Flag("device", "Arduino connected to USB").
Default("/dev/ttyUSB0").String()
listenAddr = kingpin.Flag("listen-address", "The address to listen on for HTTP requests").
Default(":8080").String()
configFile = kingpin.Arg("config.yaml", "Path to config file.").String()
temperature *prometheus.GaugeVec
humidity *prometheus.GaugeVec
)
const (
// SensorID is the unique identifier of the sensor
SensorID = "id"
// SensorLocation is the location where the sensor is placed
SensorLocation = "location"
)
func main() {
kingpin.Parse()
loadConfig(*configFile)
setupMetrics()
http.Handle("/metrics", promhttp.Handler())
SetupDevice(*device)
dev, err := OpenDevice(*device)
if err != nil {
log.Fatalf("Could not open '%v'", *device)
}
defer dev.Close()
err = dev.Reset()
if err != nil {
log.Fatalf("Could not reset '%v'", *device)
}
go receive(dev)
log.Printf("Serving metrics at '%v/metrics'", *listenAddr)
log.Fatal(http.ListenAndServe(*listenAddr, nil))
}
func setupMetrics() {
temperature = prometheus.NewGaugeVec(prometheus.GaugeOpts{
Name: "meter_temperature_celsius",
Help: "Current temperature in Celsius",
}, []string{
SensorID,
SensorLocation,
})
humidity = prometheus.NewGaugeVec(prometheus.GaugeOpts{
Name: "meter_humidity_percent",
Help: "Current humidity level in %",
}, []string{
SensorID,
SensorLocation,
})
prometheus.MustRegister(temperature)
prometheus.MustRegister(humidity)
}
func receive(a *Device) {
// tell the Arduino to start receiving signals
err := a.Write(ReceiveCmd)
if err != nil {
log.Fatalf("Could not write to '%v'", a)
}
log.Println("Write", ReceiveCmd)
ctx := context.Background()
// read and decode received signals forever
err = a.Process(ctx, DecodedSignal)
if err != nil {
log.Println(err)
}
}
// DecodedSignal decodes a compressed signal read from the Arduino
// by trying all currently supported protocols and stores result for Prometheus scraping
func DecodedSignal(line string) (stop bool) {
stop = false
if strings.HasPrefix(line, ReceivePrefix) {
trimmed := strings.TrimPrefix(line, ReceivePrefix)
pulse, err := PreparePulse(trimmed)
if err != nil {
log.Println(err)
return
}
matchingProtocols := MatchingProtocols(pulse)
if !processedWithMatchingConfig(matchingProtocols, pulse) {
printAllMatchingProtocols(matchingProtocols, pulse)
}
}
return
}
func printAllMatchingProtocols(matchingProtocols []string, pulse *Signal) {
firstMatch := true
for _, p := range matchingProtocols {
result, err := DecodePulse(pulse, p)
if err != nil {
log.Println(err)
continue
}
m := result.(*GTWT01Result)
if firstMatch {
log.Println("Sensor has no matching configuration, potential protocols:")
firstMatch = false
}
log.Printf("%v: %+v\n", p, *m)
}
if firstMatch {
log.Println("Unsupported protocol or error decoding the pulse")
} else {
log.Println("Add to configuration with appropriate protocol")
}
}
func processedWithMatchingConfig(matchingProtocols []string, pulse *Signal) bool {
protocolMatch := false
configuredSensors := vip.GetStringMap("sensors")
for id := range configuredSensors {
location := vip.GetString(fmt.Sprintf("sensors.%s.location", id))
if location == "" {
panic(fmt.Errorf("fatal error sensor id %s has no location specified in config file", id))
}
protocol := vip.GetString(fmt.Sprintf("sensors.%s.protocol", id))
if protocol == "" {
panic(fmt.Errorf("fatal error sensor id %s has no protocol specified in config file", id))
}
for _, p := range matchingProtocols {
if p == protocol {
result, err := DecodePulse(pulse, protocol)
if err != nil {
log.Println(err)
break
}
m := result.(*GTWT01Result)
if m.Name == id {
temperature.With(prometheus.Labels{
SensorID: m.Name,
SensorLocation: location,
}).Set(m.Temperature)
humidity.With(prometheus.Labels{
SensorID: m.Name,
SensorLocation: location,
}).Set(float64(m.Humidity))
log.Printf("%v: %+v\n", location, *m)
protocolMatch = true
break
}
}
}
}
return protocolMatch
}