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
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
|
package status // import "hhvn.uk/hbspbar/status"
import (
"fmt"
"errors"
"strings"
"hhvn.uk/hbspbar/common"
)
func getcpus(c chan [][]string, e chan error) {
var ret [][]string
lines, err := common.FileAsLines("/proc/stat")
if err != nil {
c <- nil
e <- err
return
}
for _, l := range lines {
var tok []string
tokempty := strings.Split(l, " ")
if !strings.HasPrefix(tokempty[0], "cpu") ||
strings.HasSuffix(tokempty[0], "u") {
continue
}
for _, t := range tokempty {
if t != "" { tok = append(tok, t) }
}
ret = append(ret, tok)
}
c <- ret
// This is only used if ret == nil
e <- errors.New("apparently this computer has no cores")
}
func cpu(name string) error {
u := newUpdate(name)
cpus := [2]chan [][]string{
make(chan [][]string),
make(chan [][]string) }
cpuerr := [2]chan error{
make(chan error),
make(chan error) }
go getcpus(cpus[0], cpuerr[0])
sleep(1)
go getcpus(cpus[1], cpuerr[1])
start := <- cpus[0]
if start == nil { return <- cpuerr[0] }
end := <- cpus[1]
if end == nil { return <- cpuerr[1] }
if len(start) != len(end) {
return errors.New("somehow we lost/gained some cores")
}
ncores := len(start)
total := make([]int, ncores)
idle := make([]int, ncores)
for i, c := range start {
for j, v := range c {
if j == 0 { continue }
n, err := common.Intify(v)
if err != nil { return err }
total[i] += n
}
n, err := common.Intify(c[4])
if err != nil { return err }
idle[i] = n
}
cx := 0
for i, c := range end {
ltotal := 0
for j, v := range c {
if j == 0 { continue }
n, err := common.Intify(v)
if err != nil { return err }
ltotal += n
}
n, err := common.Intify(c[4])
if err != nil { return err }
lidle := n - idle[i]
ltotal = ltotal - total[i]
used := int((100 * (ltotal - lidle)) / ltotal)
cx += u.drawPercentBar(cx, used)
}
temps := 0
for i := 0; i < ncores; i ++ {
file := fmt.Sprintf("/sys/class/thermal/thermal_zone%d/temp", i)
content, err := common.FileAsLines(file)
if err != nil { return err }
n, err := common.Intify(content[0])
if err != nil { return err }
temps += n / 1000
}
// <=40: green. >=80: red.
cp := float64(temps/ncores - 40)
cp /= 40
cp *= 100
if cp > 100 { cp = 100 }
u.drawText(cx, blendGYR(int(cp)), fmt.Sprintf("%d°C", temps / ncores))
updates <- u
return nil
}
func init() {
name := "cpu"
register(name)
go func(){
for {
checkError(name, cpu(name))
}
}()
}
|