-
Notifications
You must be signed in to change notification settings - Fork 12
/
Copy pathmain.go
287 lines (242 loc) · 8.01 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
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
package main
import (
"context"
"encoding/json"
"errors"
"flag"
"fmt"
"log"
"net/http"
"os"
"os/signal"
"syscall"
switchbot "github.com/nasa9084/go-switchbot/v4"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promhttp"
)
var (
listenAddress = flag.String("web.listen-address", ":8080", "The address to listen on for HTTP requests")
openToken = flag.String("switchbot.open-token", "", "The open token for switchbot-api")
secretKey = flag.String("switchbot.secret-key", "", "The secret key for switchbot-api")
)
// deviceLabels is global cache gauge which stores device id and device name as its label.
var deviceLabels = prometheus.NewGaugeVec(prometheus.GaugeOpts{
Namespace: "switchbot",
Name: "device",
}, []string{"device_id", "device_name"})
// the type expected by the prometheus http service discovery
type StaticConfig struct {
Targets []string `json:"targets"`
Labels map[string]string `json:"labels"`
}
func main() {
flag.Parse()
if err := run(); err != nil {
log.Printf("error: %v", err)
os.Exit(1)
}
}
func run() error {
openTokenFromEnv := os.Getenv("SWITCHBOT_OPENTOKEN")
if openTokenFromEnv != "" {
*openToken = openTokenFromEnv
}
if *openToken == "" {
return errors.New("-switchbot.open-token is required")
}
secretKeyFromEnv := os.Getenv("SWITCHBOT_SECRETKEY")
if secretKeyFromEnv != "" {
*secretKey = secretKeyFromEnv
}
if *secretKey == "" {
return errors.New("-switchbot.secret-key is required")
}
sc := switchbot.New(*openToken, *secretKey)
if err := reloadDevices(sc); err != nil {
return err
}
hup := make(chan os.Signal, 1)
reloadCh := make(chan chan error)
signal.Notify(hup, syscall.SIGHUP)
go func() {
// reload
for {
select {
case <-hup:
if err := reloadDevices(sc); err != nil {
log.Printf("error reloading devices: %v", err)
}
log.Print("reloaded devices")
case errCh := <-reloadCh:
if err := reloadDevices(sc); err != nil {
log.Printf("error relaoding devices: %v", err)
errCh <- err
} else {
errCh <- nil
}
log.Print("relaoded devices")
}
}
}()
http.HandleFunc("/discover", func(w http.ResponseWriter, r *http.Request) {
log.Printf("discovering devices...")
devices, _, err := sc.Device().List(r.Context())
if err != nil {
http.Error(w, fmt.Sprintf("failed to discover devices: %s", err), http.StatusInternalServerError)
return
}
log.Printf("discovered device count: %d", len(devices))
supportedDeviceTypes := map[switchbot.PhysicalDeviceType]struct{}{
switchbot.Hub2: {},
switchbot.Humidifier: {},
switchbot.Meter: {},
switchbot.MeterPlus: {},
switchbot.MeterPro: {},
switchbot.MeterProCO2: {},
switchbot.PlugMiniJP: {},
switchbot.WoIOSensor: {},
}
data := make([]StaticConfig, len(devices))
for i, device := range devices {
_, deviceTypeIsSupported := supportedDeviceTypes[device.Type]
if !deviceTypeIsSupported {
log.Printf("ignoring device %s with unsupported type: %s", device.ID, device.Type)
continue
}
log.Printf("discovered device %s of type %s", device.ID, device.Type)
staticConfig := StaticConfig{}
staticConfig.Targets = make([]string, 1)
staticConfig.Labels = make(map[string]string)
staticConfig.Targets[0] = device.ID
staticConfig.Labels["device_id"] = device.ID
staticConfig.Labels["device_name"] = device.Name
staticConfig.Labels["device_type"] = string(device.Type)
data[i] = staticConfig
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
json.NewEncoder(w).Encode(data)
})
http.HandleFunc("/-/reload", func(w http.ResponseWriter, r *http.Request) {
if expectMethod := http.MethodPost; r.Method != expectMethod {
w.WriteHeader(http.StatusMethodNotAllowed)
fmt.Fprintf(w, "This endpoint requires a %s request.\n", expectMethod)
return
}
rc := make(chan error)
reloadCh <- rc
if err := <-rc; err != nil {
http.Error(w, fmt.Sprintf("failed to reload config: %s", err), http.StatusInternalServerError)
}
})
http.HandleFunc("/metrics", func(w http.ResponseWriter, r *http.Request) {
registry := prometheus.NewRegistry()
target := r.FormValue("target")
if target == "" {
http.Error(w, "target parameter is missing", http.StatusBadRequest)
return
}
log.Printf("getting device status: %s", target)
status, err := sc.Device().Status(r.Context(), target)
if err != nil {
log.Printf("getting device status: %v", err)
return
}
log.Printf("got device status: %s", target)
switch status.Type {
case switchbot.Meter, switchbot.MeterPlus, switchbot.MeterPro, switchbot.Hub2, switchbot.WoIOSensor, switchbot.Humidifier:
meterHumidity := prometheus.NewGaugeVec(prometheus.GaugeOpts{
Namespace: "switchbot",
Subsystem: "meter",
Name: "humidity",
}, []string{"device_id"})
meterTemperature := prometheus.NewGaugeVec(prometheus.GaugeOpts{
Namespace: "switchbot",
Subsystem: "meter",
Name: "temperature",
}, []string{"device_id"})
registry.MustRegister(deviceLabels) // register global device labels cache
registry.MustRegister(meterHumidity, meterTemperature)
meterHumidity.WithLabelValues(status.ID).Set(float64(status.Humidity))
meterTemperature.WithLabelValues(status.ID).Set(status.Temperature)
case switchbot.MeterProCO2:
meterCO2 := prometheus.NewGaugeVec(prometheus.GaugeOpts{
Namespace: "switchbot",
Subsystem: "meter",
Name: "CO2",
}, []string{"device_id"})
meterHumidity := prometheus.NewGaugeVec(prometheus.GaugeOpts{
Namespace: "switchbot",
Subsystem: "meter",
Name: "humidity",
}, []string{"device_id"})
meterTemperature := prometheus.NewGaugeVec(prometheus.GaugeOpts{
Namespace: "switchbot",
Subsystem: "meter",
Name: "temperature",
}, []string{"device_id"})
registry.MustRegister(deviceLabels) // register global device labels cache
registry.MustRegister(meterCO2, meterHumidity, meterTemperature)
meterCO2.WithLabelValues(status.ID).Set(float64(status.CO2))
meterHumidity.WithLabelValues(status.ID).Set(float64(status.Humidity))
meterTemperature.WithLabelValues(status.ID).Set(status.Temperature)
case switchbot.PlugMiniJP:
plugWeight := prometheus.NewGaugeVec(prometheus.GaugeOpts{
Namespace: "switchbot",
Subsystem: "plug",
Name: "weight",
}, []string{"device_id"})
plugVoltage := prometheus.NewGaugeVec(prometheus.GaugeOpts{
Namespace: "switchbot",
Subsystem: "plug",
Name: "voltage",
}, []string{"device_id"})
plugElectricCurrent := prometheus.NewGaugeVec(prometheus.GaugeOpts{
Namespace: "switchbot",
Subsystem: "plug",
Name: "electricCurrent",
}, []string{"device_id"})
registry.MustRegister(deviceLabels)
registry.MustRegister(plugWeight, plugVoltage, plugElectricCurrent)
plugWeight.WithLabelValues(status.ID).Set(status.Weight)
plugVoltage.WithLabelValues(status.ID).Set(status.Voltage)
plugElectricCurrent.WithLabelValues(status.ID).Set(status.ElectricCurrent)
default:
log.Printf("unrecognized device type: %s", status.Type)
}
promhttp.HandlerFor(registry, promhttp.HandlerOpts{}).ServeHTTP(w, r)
})
srv := &http.Server{Addr: *listenAddress}
srvc := make(chan error)
term := make(chan os.Signal, 1)
signal.Notify(term, os.Interrupt, syscall.SIGTERM)
go func() {
if err := srv.ListenAndServe(); err != http.ErrServerClosed {
srvc <- err
}
}()
for {
select {
case <-term:
log.Print("received terminate signal")
return nil
case err := <-srvc:
return err
}
}
}
func reloadDevices(sc *switchbot.Client) error {
log.Print("reload device list")
devices, infrared, err := sc.Device().List(context.Background())
if err != nil {
return fmt.Errorf("getting device list: %w", err)
}
log.Print("got device list")
for _, device := range devices {
deviceLabels.WithLabelValues(device.ID, device.Name).Set(0)
}
for _, device := range infrared {
deviceLabels.WithLabelValues(device.ID, device.Name).Set(0)
}
return nil
}