-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtemperature.go
90 lines (74 loc) · 2.24 KB
/
temperature.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
package main
import (
"encoding/json"
"errors"
"os/exec"
"reflect"
"runtime"
"slices"
"strings"
)
type JsonMap = map[string]any
// Return the temp (if found) along with whether the temp was present/found or not.
func extractTemp(jsonMap JsonMap) (float64, bool) {
hasFound := false
extractedTemp := float64(0)
// Recurse until you found the temp
for key, value := range jsonMap {
if strings.Contains(key, "temp") && strings.Contains(key, "input") {
if temp, ok := value.(float64); ok {
extractedTemp += temp
hasFound = true
}
} else if reflect.TypeOf(value).Kind() == reflect.Map {
if valueAsJson, ok := value.(JsonMap); ok {
extractedTemp2, hasFound2 := extractTemp(valueAsJson)
if hasFound2 {
extractedTemp += extractedTemp2
hasFound = true
}
}
}
}
return extractedTemp, hasFound
}
// Use a platform dependant API like `lm-sensors` in linux to get the temperature
// of hardwares whose names match the names of elements in `sensors`
// and then parse the information and return it.
func getAvgTempOfSensors(sensors []string) (float64, error) {
avgCpuTemp := float64(0)
switch runtime.GOOS {
case "darwin": // AKA mac
// Nice joke
case "linux":
// Use sensors (AKA lm-sensors) to get the temps in JSON
// and then take average temp from the parsed JSON and return.
// Return an error if something goes wrong.
command := exec.Command("sensors", "-j")
outputAsBytesArray, commandErr := command.Output()
if commandErr != nil {
return 0.0, commandErr
}
tempsJson := map[string]JsonMap{}
if jsonParsingError := json.Unmarshal(outputAsBytesArray, &tempsJson); jsonParsingError != nil {
return 0.0, jsonParsingError
}
hardwareTempSum := float64(0)
hardwareCount := float64(0)
for hardwareName, value := range tempsJson {
if slices.Contains(sensors, hardwareName) {
tempOfHardware, hadTemperatureReading := extractTemp(value)
if hadTemperatureReading {
hardwareTempSum += tempOfHardware
hardwareCount++
}
}
}
avgCpuTemp = hardwareTempSum / hardwareCount
return avgCpuTemp, nil
case "windows":
// Maybe TODO if I start using windows again
}
// If it has reached this line, then the OS was not supported.
return 0.0, errors.New("OS not supported")
}