-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathsmart_plugs.go
69 lines (63 loc) · 1.96 KB
/
smart_plugs.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
package main
import (
"context"
"encoding/json"
"github.com/tess1o/tapo-go"
"log/slog"
)
type SmartPlug struct {
Name string `json:"name"`
Host string `json:"host"`
Client *tapo.SmartPlug `json:"-"`
Exporter *PrometheusExporter `json:"-"`
Username string `json:"-"`
Password string `json:"-"`
}
func (s SmartPlug) GetEnergyUsage() (*tapo.EnergyUsageResponse, error) {
return s.Client.GetEnergyUsage()
}
func initSmartPlugs(devices []*SmartPlug, username string, password string, exporter *PrometheusExporter) {
for i := range devices {
devices[i].Exporter = exporter
devices[i].Username = username
devices[i].Password = password
client, err := initSmartPlugClient(devices[i])
if err != nil {
slog.Error("Failed to create Tapo client", "error", err, "device", devices[i].Name)
continue
}
devices[i].Client = client
}
}
func initSmartPlugClient(plug *SmartPlug) (*tapo.SmartPlug, error) {
slog.Info("Creating Tapo client", "host", plug.Host)
return tapo.NewSmartPlug(plug.Host, plug.Username, plug.Password, tapo.Options{
RetryConfig: tapo.DefaultRetryConfig,
})
}
func handleSmartPlug(device *SmartPlug) {
if device.Client == nil {
client, err := initSmartPlugClient(device)
if err != nil {
slog.Error("Failed to create Tapo client", "error", err, "device", device.Name)
return
}
device.Client = client
}
r, err := device.GetEnergyUsage()
if err != nil {
slog.Error("Error getting energy usage", "device", device.Name, "error", err)
client, initErr := initSmartPlugClient(device)
if initErr != nil {
slog.Error("Failed to create Tapo client", "error", initErr, "device", device.Name)
return
}
device.Client = client
} else {
slog.Info("Successfully received metrics", "device", device.Name)
d, _ := json.Marshal(r.Result)
var params map[string]interface{}
json.Unmarshal(d, ¶ms)
device.Exporter.HandleSmartPlug(context.Background(), device, params)
}
}