forked from gunnaringe/tibber-exporter
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
277 lines (262 loc) · 7.14 KB
/
Copy pathmain.go
File metadata and controls
277 lines (262 loc) · 7.14 KB
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
package main
import (
"context"
"github.com/jessevdk/go-flags"
"github.com/machinebox/graphql"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promauto"
"github.com/prometheus/client_golang/prometheus/promhttp"
"log"
"net/http"
"os"
"time"
)
var opts struct {
Token string `short:"t" long:"token" description:"Authorization token" required:"true" env:"TIBBER_TOKEN"`
Endpoint string `short:"e" long:"endpoint" description:"Endpoint" required:"false" env:"TIBBER_ENDPOINT" default:"https://api.tibber.com/v1-beta/gql"`
Listen string `short:"l" long:"listen" description:"Address and port to listen" env:"TIBBER_LISTEN" default:":9501"`
Verbose []bool `short:"v" long:"verbose" description:"Show verbose debug information"`
}
var client *graphql.Client
var (
namespace = "tibber"
requestsTotal = promauto.NewCounter(prometheus.CounterOpts{
Namespace: namespace,
Name: "requests_total",
Help: "Number of requests done by exporter",
})
lastScrapeDuration = promauto.NewGauge(prometheus.GaugeOpts{
Namespace: namespace,
Name: "scrape_duration_seconds",
Help: "Scrape duration of last scrape",
})
info = promauto.NewGaugeVec(
prometheus.GaugeOpts{
Namespace: namespace,
Name: "home_info",
Help: "Home information",
},
[]string{
"home_id",
"time_zone",
"address1",
"address2",
"address3",
"city",
"postal_code",
"country",
"latitude",
"longitude",
})
priceInfoCurrentTotal = promauto.NewGaugeVec(
prometheus.GaugeOpts{
Namespace: namespace,
Name: "current_energy_price",
Help: "Current energy price",
},
[]string{
"home_id",
"type",
"currency",
})
lastPeriodConsumption = promauto.NewGaugeVec(
prometheus.GaugeOpts{
Namespace: namespace,
Name: "previous_hour_consumption_watt_hour",
Help: "Total Watt hours used last hourly period",
},
[]string{
"home_id",
})
lastPeriodTotalCost = promauto.NewGaugeVec(
prometheus.GaugeOpts{
Namespace: namespace,
Name: "previous_hour_total_cost",
Help: "Total cost last hourly period",
},
[]string{
"home_id",
"currency",
})
lastPeriodPrice = promauto.NewGaugeVec(
prometheus.GaugeOpts{
Namespace: namespace,
Name: "previous_hour_energy_price",
Help: "Energy price last hourly period",
},
[]string{
"home_id",
"type",
"currency",
})
)
type Response struct {
Viewer struct {
Name string `json:"name"`
Homes []struct {
Id string `json:"id"`
TimeZone string `json:"timeZone"`
Address struct {
Address1 string `json:"address1"`
Address2 string `json:"address2"`
Address3 string `json:"address3"`
City string `json:"city"`
PostalCode string `json:"postalCode"`
Country string `json:"country"`
Latitude string `json:"latitude"`
Longitude string `json:"longitude"`
} `json:"address"`
Owner struct {
FirstName string `json:"firstName"`
LastName string `json:"lastName"`
ContactInfo struct {
Email string `json:"email"`
Mobile string `json:"mobile"`
} `json:"contactInfo"`
} `json:"owner"`
CurrentSubscription struct {
PriceInfo struct {
Current struct {
Total float64 `json:"total"`
Energy float64 `json:"energy"`
Tax float64 `json:"tax"`
Currency string `json:"currency"`
StartsAt time.Time `json:"startsAt"`
Level string `json:"level"`
} `json:"current"`
} `json:"priceInfo"`
} `json:"currentSubscription"`
Consumption struct {
Nodes []struct {
From time.Time `json:"from"`
To time.Time `json:"to"`
TotalCost float64 `json:"totalCost"`
UnitCost float64 `json:"unitCost"`
UnitPrice float64 `json:"unitPrice"`
UnitPriceVAT float64 `json:"unitPriceVAT"`
Consumption float64 `json:"consumption"`
ConsumptionUnit string `json:"consumptionUnit"`
Currency string `json:"currency"`
} `json:"nodes"`
} `json:"consumption"`
} `json:"homes"`
} `json:"viewer"`
}
func updatePrometheus(response Response, scrapeDuration float64) {
requestsTotal.Inc()
lastScrapeDuration.Set(scrapeDuration)
for _, home := range response.Viewer.Homes {
info.WithLabelValues(
home.Id,
home.TimeZone,
home.Address.Address1,
home.Address.Address2,
home.Address.Address3,
home.Address.City,
home.Address.PostalCode,
home.Address.Country,
home.Address.Latitude,
home.Address.Longitude).Set(1)
currentSubscription := home.CurrentSubscription
priceInfoCurrentTotal.WithLabelValues(home.Id, "energy", currentSubscription.PriceInfo.Current.Currency).Set(currentSubscription.PriceInfo.Current.Energy)
priceInfoCurrentTotal.WithLabelValues(home.Id, "tax", currentSubscription.PriceInfo.Current.Currency).Set(currentSubscription.PriceInfo.Current.Tax)
if len(home.Consumption.Nodes) > 0 {
node := home.Consumption.Nodes[0]
if node.ConsumptionUnit != "kWh" {
log.Printf("Expected unit kWh, but got %s\n", node.ConsumptionUnit)
}
// Use base unit; Wh instead of kWh
lastPeriodConsumption.WithLabelValues(home.Id).Set(node.Consumption / 1000)
lastPeriodPrice.WithLabelValues(home.Id, "energy", node.Currency).Set(node.UnitPrice)
lastPeriodPrice.WithLabelValues(home.Id, "vat", node.Currency).Set(node.UnitPriceVAT)
lastPeriodTotalCost.WithLabelValues(home.Id, node.Currency).Set(node.TotalCost)
}
}
}
func scrape() Response {
req := graphql.NewRequest(`
{
viewer {
name
homes {
id
timeZone
address {
address1
address2
address3
city
postalCode
country
latitude
longitude
}
owner {
firstName
lastName
contactInfo {
email
mobile
}
}
currentSubscription{
priceInfo{
current{
total
energy
tax
currency
startsAt
level
}
}
}
consumption(resolution: HOURLY, last: 1) {
nodes {
from
to
totalCost
unitCost
unitPrice
unitPriceVAT
consumption
consumptionUnit
currency
}
}
}
}
}
`)
req.Header.Set("Authorization", opts.Token)
ctx := context.Background()
var response Response
if err := client.Run(ctx, req, &response); err != nil {
log.Fatal(err)
}
return response
}
type updater struct {
h http.Handler
}
func (c updater) ServeHTTP(w http.ResponseWriter, r *http.Request) {
start := time.Now()
response := scrape()
scrapeDuration := time.Since(start).Seconds()
updatePrometheus(response, scrapeDuration)
log.Println("Update OK")
c.h.ServeHTTP(w, r)
}
func main() {
_, err := flags.Parse(&opts)
if err != nil {
os.Exit(1)
}
client = graphql.NewClient(opts.Endpoint)
if len(opts.Verbose) > 0 {
client.Log = func(s string) { log.Println(s) }
}
log.Println("Server is listening on " + opts.Listen)
http.Handle("/", promhttp.Handler())
log.Println(http.ListenAndServe(opts.Listen, updater{http.DefaultServeMux}))
}