-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
102 lines (88 loc) · 2.54 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
package main
import (
"context"
"errors"
"flag"
"fmt"
"net/http"
"os"
"time"
"github.com/loafoe/prometheus-solaxcloud-exporter/solaxcloud"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promhttp"
)
var listenAddr string
var debug bool
var (
metricNamePrefix = "solaxcloud_"
registry = prometheus.NewRegistry()
)
var (
yieldTodayMetric = prometheus.NewGaugeVec(prometheus.GaugeOpts{
Name: metricNamePrefix + "yield_today",
Help: "The yield for today (KWh)",
}, []string{
"inverter_sn",
})
yieldTotalMetrics = prometheus.NewGaugeVec(prometheus.GaugeOpts{
Name: metricNamePrefix + "yield_total",
Help: "The total yield of the system (KWh)",
}, []string{
"inverter_sn",
})
acPowerMetric = prometheus.NewGaugeVec(prometheus.GaugeOpts{
Name: metricNamePrefix + "ac_power",
Help: "Current power generation (Wh)",
}, []string{
"inverter_sn",
})
upMetric = prometheus.NewGaugeVec(prometheus.GaugeOpts{
Name: metricNamePrefix + "up",
Help: "The inverter power on status",
}, []string{
"sn",
})
)
func init() {
registry.MustRegister(yieldTotalMetrics)
registry.MustRegister(yieldTodayMetric)
registry.MustRegister(acPowerMetric)
registry.MustRegister(upMetric)
}
func main() {
flag.BoolVar(&debug, "debug", false, "Enable debugging")
flag.StringVar(&listenAddr, "listen", "0.0.0.0:8887", "Listen address for HTTP metrics")
flag.Parse()
sn := os.Getenv("SOLAXCLOUD_SN")
tokenId := os.Getenv("SOLAXCLOUD_TOKEN_ID")
go func() {
sleep := false
for {
if sleep {
time.Sleep(time.Second * 60) // 5 minute resolution, so we poll every minute for now
}
sleep = true
ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
fmt.Printf("calling SolaxCloud...\n")
resp, err := solaxcloud.GetRealtimeInfo(ctx,
solaxcloud.WithSNAndTokenID(sn, tokenId),
solaxcloud.WithDebug(debug))
cancel()
if err != nil {
fmt.Printf("error: %v\n", err)
upMetric.WithLabelValues(sn).Set(0)
if errors.Is(err, context.DeadlineExceeded) {
fmt.Printf("not sleeping\n")
sleep = false
}
continue
}
yieldTodayMetric.WithLabelValues(resp.Result.InverterSN).Set(resp.Result.YieldToday)
yieldTotalMetrics.WithLabelValues(resp.Result.InverterSN).Set(resp.Result.YieldTotal)
acPowerMetric.WithLabelValues(resp.Result.InverterSN).Set(resp.Result.ACPower)
upMetric.WithLabelValues(sn).Set(1.0)
}
}()
http.Handle("/metrics", promhttp.HandlerFor(registry, promhttp.HandlerOpts{}))
_ = http.ListenAndServe(listenAddr, nil)
}