-
Notifications
You must be signed in to change notification settings - Fork 0
/
metrics.go
80 lines (64 loc) · 1.92 KB
/
metrics.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
package client
import (
"context"
"fmt"
"strconv"
"github.com/kklipsch/reagle/local"
)
//BaseMetrics are the most commonly used metrics on the smart meter
type BaseMetrics struct {
Demand float64 `json:"demand"`
Delivered float64 `json:"delivered"`
Price float64 `json:"price"`
Currency string `json:"currency"`
}
func getBaseMetrics(ctx context.Context, localAPI local.API, hardwareAddress string) (BaseMetrics, error) {
values := BaseMetrics{}
response, err := localAPI.DeviceQuery(ctx, hardwareAddress, "zigbee:InstantaneousDemand", "zigbee:CurrentSummationDelivered", "zigbee:Price", "zigbee:PriceCurrency")
if err != nil {
return values, fmt.Errorf("call to api failed: %v", err)
}
variables := local.ResultsFromDetailsResponse(response)
if len(variables) != 1 {
return values, fmt.Errorf("variables has more components than expected: %v", variables)
}
var component map[string]local.Variable
for _, component = range variables {
break
}
values.Demand, err = getValueFloat("zigbee:InstantaneousDemand", component)
if err != nil {
return values, err
}
values.Delivered, err = getValueFloat("zigbee:CurrentSummationDelivered", component)
if err != nil {
return values, err
}
values.Price, err = getValueFloat("zigbee:Price", component)
if err != nil {
return values, err
}
values.Currency, err = getValue("zigbee:PriceCurrency", component)
return values, err
}
func getValue(name string, v map[string]local.Variable) (string, error) {
variable, ok := v[name]
if !ok {
return "", fmt.Errorf("%v does not exist: %v", name, v)
}
return variable.Value, nil
}
func getValueFloat(name string, v map[string]local.Variable) (float64, error) {
value, err := getValue(name, v)
if err != nil {
return 0, err
}
if value == "undefined" {
return 0, nil
}
result, err := strconv.ParseFloat(value, 64)
if err != nil {
return 0, fmt.Errorf("%s:%s - %v", name, value, err)
}
return result, nil
}