-
Notifications
You must be signed in to change notification settings - Fork 0
/
w1_therm_exporter.go
117 lines (94 loc) · 2.65 KB
/
w1_therm_exporter.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
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
package main
import (
"fmt"
"io/ioutil"
"log"
"net/http"
"strconv"
"strings"
"time"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promhttp"
"flag"
)
var (
tempVec = prometheus.NewGaugeVec(
prometheus.GaugeOpts{
Namespace: "w1",
Subsystem: "therm",
Name: "temperature_celsius",
Help: "Temperatures in Celsius read via w1_therm linux kernel module",
},
[]string{"sensor_id"},
)
currentSensors = make(map[string]int64)
)
func init() {
// Metrics have to be registered to be exposed:
prometheus.MustRegister(tempVec)
}
func main() {
go func() {
for {
// Fetch list of sensors
sensorsList, err := ioutil.ReadDir("/sys/bus/w1/devices/")
if err != nil {
log.Fatal(err)
}
// Iterate over list of sensors
for _, sensor := range sensorsList {
// Fetch sensors current value as file
file, err := ioutil.ReadFile("/sys/bus/w1/devices/" + sensor.Name() + "/w1_slave")
if err != nil {
continue
}
str := string(file)
// Check for correct checksum
if !strings.Contains(str, "YES") {
tempVec.DeleteLabelValues(sensor.Name())
continue
}
// Extract temperature value (Celsius) from file
slc := strings.SplitAfter(str, "t=")
// Check if there is an valid string in file
if len(slc) < 2 {
continue
}
str = slc[1]
// Remove unnecessary characters
str = strings.Replace(str, "\n", "", -1)
str = strings.Replace(str, "\r", "", -1)
str = strings.Replace(str, "\t", "", -1)
// Convert string to float
tempInt, err := strconv.Atoi(str)
if err != nil {
continue
}
// Correct formatting
tempInt = tempInt / 100
tempFloat := float64(tempInt) / 10
// Print to stdout and add to / update gauge vector
fmt.Println(sensor.Name(), tempFloat)
tempVec.WithLabelValues(sensor.Name()).Set(tempFloat)
// Refresh timeout
currentSensors[sensor.Name()] = time.Now().UTC().Unix()
}
// Remove timed out sensors from gauge vector
for name, timestamp := range currentSensors {
// Check if last value is older than 5 min
if (timestamp + 300) < time.Now().UTC().Unix() {
tempVec.DeleteLabelValues(name)
delete(currentSensors, name)
}
}
// Give 1w bus time for some housekeeping
time.Sleep(10 * time.Second)
}
}()
httpAddr := flag.String("httpAddr", "0.0.0.0:8080", "HTTP Address")
flag.Parse()
// The Handler function provides a default handler to expose metrics
// via an HTTP server. "/metrics" is the usual endpoint for that.
http.Handle("/metrics", promhttp.Handler())
log.Fatal(http.ListenAndServe(*httpAddr, nil))
}