forked from davidscholberg/goblocks
/
temperature.go
84 lines (81 loc) · 2.05 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
package modules
import (
"fmt"
"github.com/davidscholberg/go-i3barjson"
"io/ioutil"
"os"
"strings"
)
// Temperature represents the configuration for the CPU temperature block.
// CpuTempPath is the path to the "hwmon" directory of the CPU temperature info.
// e.g. /sys/devices/platform/coretemp.0/hwmon
type Temperature struct {
BlockConfigBase `yaml:",inline"`
CpuTempPath string `yaml:"cpu_temp_path"`
CritTemp float64 `yaml:"crit_temp"`
}
// UpdateBlock updates the CPU temperature info.
// The value output by the block is the average temperature of all cores.
func (c Temperature) UpdateBlock(b *i3barjson.Block) {
b.Color = c.Color
fullTextFmt := fmt.Sprintf("%s%%s", c.Label)
totalTemp := 0
procs := 0
sysFileDirList, err := ioutil.ReadDir(c.CpuTempPath)
if err != nil {
b.Urgent = true
b.FullText = fmt.Sprintf(fullTextFmt, err.Error())
return
}
if len(sysFileDirList) != 1 {
b.Urgent = true
msg := fmt.Sprintf(
"in %s, expected 1 file, got %d",
c.CpuTempPath,
len(sysFileDirList),
)
b.FullText = fmt.Sprintf(fullTextFmt, msg)
return
}
sysFileDirPath := fmt.Sprintf(
"%s/%s",
c.CpuTempPath,
sysFileDirList[0].Name(),
)
sysFileNameFmt := fmt.Sprintf("%s/%%s", sysFileDirPath)
sysFiles, err := ioutil.ReadDir(sysFileDirPath)
if err != nil {
b.Urgent = true
b.FullText = fmt.Sprintf(fullTextFmt, err.Error())
return
}
for _, sysFile := range sysFiles {
sysFileName := sysFile.Name()
if !strings.HasSuffix(sysFileName, "input") {
continue
}
r, err := os.Open(fmt.Sprintf(sysFileNameFmt, sysFileName))
if err != nil {
b.Urgent = true
b.FullText = fmt.Sprintf(fullTextFmt, err.Error())
return
}
defer r.Close()
var temp int
_, err = fmt.Fscanf(r, "%d", &temp)
if err != nil {
b.Urgent = true
b.FullText = fmt.Sprintf(fullTextFmt, err.Error())
return
}
totalTemp += temp
procs++
}
avgTemp := float64(totalTemp) / float64(procs*1000)
if avgTemp >= c.CritTemp {
b.Urgent = true
} else {
b.Urgent = false
}
b.FullText = fmt.Sprintf("%s%.2f°C", c.Label, avgTemp)
}