-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathha_metric.go
More file actions
99 lines (78 loc) · 1.9 KB
/
ha_metric.go
File metadata and controls
99 lines (78 loc) · 1.9 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
package main
import (
"context"
"fmt"
"strconv"
"github.com/fagnercarvalho/ha-influx-grafana/ha"
"github.com/fagnercarvalho/ha-influx-grafana/metrics"
)
func addMetric(ctx context.Context, entityID string, homeAssistant ha.HomeAssistant, meter metrics.Meter) error {
getMetric := func() (metrics.Metric, error) {
currentState, err := homeAssistant.GetStateByEntityID(ctx, entityID)
if err != nil {
return metrics.Metric{}, err
}
metric, err := convertToMetric(currentState)
if err != nil {
return metrics.Metric{}, err
}
return metric, nil
}
metric, err := getMetric()
if err != nil {
return err
}
metric.GetValue = func() float64 {
metric, err := getMetric()
if err != nil {
panic(err)
}
return metric.Value
}
return meter.NewGauge(metric)
}
func convertToMetric(state ha.State) (metrics.Metric, error) {
stateAsInt := convertOnOffToInteger(state.State)
parsedState, err := strconv.ParseFloat(stateAsInt, 64)
if err != nil {
fmt.Printf("Error to parse state for %v: %v. Using -1 as state value \n", state.EntityID, err)
parsedState = -1
}
metric := metrics.Metric{
Name: state.EntityID,
Value: parsedState,
// https://ucum.nlm.nih.gov/ucum-lhc/
// https://ucum.org/ucum#para-curly
Attributes: map[string]interface{}{},
}
for attribute, value := range state.Attributes {
metric.Attributes[attribute] = value
if attribute == UnitOfMeasurementAttribute {
value, ok := value.(string)
if ok {
metric.Unit = convertUnitToUCUM(value)
}
}
}
fmt.Println("Converted Home Assistant state to OTel metric", metric)
return metric, nil
}
func convertUnitToUCUM(unit string) string {
switch unit {
case "°C":
return "Cel"
case "µg/m³":
return "ug/m3"
case "%":
return unit
}
return unit
}
func convertOnOffToInteger(state string) string {
if state == "on" {
return "1"
} else if state == "off" {
return "0"
}
return state
}