-
-
Notifications
You must be signed in to change notification settings - Fork 2
/
cpu_temp.go
86 lines (78 loc) · 1.61 KB
/
cpu_temp.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
package main
import (
"fmt"
"log"
"os"
"regexp"
"strconv"
"strings"
"time"
)
var match_temp = regexp.MustCompile(`Core\s+\d+:\s+\+([\d]+)`)
type CpuTemp struct {
val string
inputs []string
}
func (k *CpuTemp) value() string {
return k.val
}
func cpu_temp() element {
e := &CpuTemp{}
// collect temp inputs, this may vary based on different kernels
for i := 1; i < 128; i++ { // might have 128 cores?
p := fmt.Sprintf("/sys/class/hwmon/hwmon0/temp%d_input", i)
if file_exists(p) {
e.inputs = append(e.inputs, p)
} else {
break
}
}
if len(e.inputs) == 0 {
// look elsewhere
p := "/sys/class/thermal/thermal_zone0/temp"
if file_exists(p) {
e.inputs = append(e.inputs, p)
}
}
if len(e.inputs) == 0 {
log.Println("could not determine CPU temperature inputs")
return e
}
go func() {
for {
if val, err := e.read(); err == nil {
e.val = val
} else {
log.Printf("could not read cpu temp: %v", err)
}
time.Sleep(time.Second * 2)
}
}()
return e
}
func (k *CpuTemp) read() (string, error) {
var avg int
for _, in := range k.inputs {
data, err := os.ReadFile(in)
if err != nil {
return "", fmt.Errorf("failed to read temperature input: %s - %v", in, err)
}
s := strings.TrimSpace(string(data))
i, err := strconv.Atoi(s)
if err != nil {
return "", fmt.Errorf("failed to read temperature input: %s - %v", in, err)
}
avg += i
}
c := avg / len(k.inputs) / 1000
var color string
switch {
case c >= 80:
color = "#dc322f"
case c >= 60:
color = "#b58900"
default:
color = "#859900"
}
return fmt.Sprintf("^fg(%s)%d °C^fg()", color, c), nil
}