-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathcpu.go
226 lines (209 loc) · 5.04 KB
/
cpu.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
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
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
// SPDX-FileCopyrightText: 2022 Kent Gibson <warthog618@gmail.com>
//
// SPDX-License-Identifier: MIT
package main
import (
"bufio"
"fmt"
"log"
"os"
"strconv"
"strings"
"github.com/pkg/errors"
"github.com/warthog618/config"
"github.com/warthog618/config/dict"
)
func init() {
RegisterModule("cpu", newCPU)
}
type cpu struct {
PolledSensor
entities map[string]bool
// as read from /proc/stat
stats CPUStats
tpath string
temp int64
haveTemp bool
idlePercent float32
uptime float64
msg string
}
func newCPU(cfg *config.Config) SyncCloser {
defCfg := dict.New()
defCfg.Set("period", "1m")
defCfg.Set("entities", []string{
"temperature",
"used_percent",
})
defCfg.Set("temperature.path", "/sys/class/thermal/thermal_zone0/temp")
cfg.Append(defCfg)
period := cfg.MustGet("period").Duration()
entities := map[string]bool{}
for _, e := range cfg.MustGet("entities").StringSlice() {
entities[e] = true
}
stats, err := cpuStats()
if err != nil {
log.Fatalf("unable to read cpu stats: %v", err)
}
cpu := cpu{entities: entities, stats: stats}
if entities["temperature"] {
tpath := cfg.MustGet("temperature.path").String()
temp, err := cpuTemp(tpath)
if err == nil {
cpu.temp = temp
}
cpu.tpath = tpath
}
cpu.poller = NewPoller(period, cpu.Refresh)
return &cpu
}
func (c *cpu) Config() []EntityConfig {
var config []EntityConfig
if c.entities["used_percent"] {
cfg := map[string]interface{}{
"name": "CPU used percent",
"state_topic": "~/cpu",
"value_template": "{{(100 - value_json.idle_percent) | round(2)}}",
"unit_of_measurement": "%",
"icon": "mdi:gauge",
}
config = append(config, EntityConfig{"used_percent", "sensor", cfg})
}
if c.entities["temperature"] {
cfg := map[string]interface{}{
"name": "CPU temperature",
"state_topic": "~/cpu",
"value_template": "{{value_json.temperature | round(2) }}",
"device_class": "temperature",
"unit_of_measurement": "°C",
}
config = append(config, EntityConfig{"temperature", "sensor", cfg})
}
if c.entities["uptime"] {
cfg := map[string]interface{}{
"name": "Uptime",
"state_topic": "~/cpu",
"value_template": "{{value_json.uptime | int }}",
"device_class": "duration",
"unit_of_measurement": "s",
}
config = append(config, EntityConfig{"uptime", "sensor", cfg})
}
return config
}
// CPUStats is an array of stats read from /proc/stat.
// Entries are [user, nicer, system, idle, iowait, irq, softirq, steal, quest, guest_nice]
type CPUStats [10]uint64
func cpuStats() (CPUStats, error) {
var stats CPUStats
f, err := os.Open("/proc/stat")
if err != nil {
return stats, err
}
defer f.Close()
scanner := bufio.NewScanner(f)
if !scanner.Scan() {
return stats, scanner.Err()
}
fields := strings.Fields(scanner.Text())
numFields := len(fields)
if fields[0] != "cpu" || numFields < 8 {
return stats, errors.Errorf("bad cpu line: %v", scanner.Text())
}
numStats := numFields - 1
if numStats > len(stats) {
numStats = len(stats)
}
for i := 0; i < numStats; i++ {
v, err := strconv.ParseUint(fields[i+1], 10, 64)
if err != nil {
return stats, err
}
stats[i] = v
}
return stats, nil
}
func cpuTemp(tpath string) (int64, error) {
f, err := os.Open(tpath)
if err != nil {
return 0, err
}
defer f.Close()
scanner := bufio.NewScanner(f)
if !scanner.Scan() {
return 0, scanner.Err()
}
return strconv.ParseInt(scanner.Text(), 10, 64)
}
func (c *cpu) Publish() {
c.ps.Publish(c.topic, c.msg)
}
func uptime() (float64, error) {
f, err := os.Open("/proc/uptime")
if err != nil {
return 0, err
}
defer f.Close()
scanner := bufio.NewScanner(f)
if !scanner.Scan() {
return 0, scanner.Err()
}
return strconv.ParseFloat(strings.Fields(scanner.Text())[0], 32)
}
func (c *cpu) Refresh(forced bool) {
changed := forced
if c.entities["uptime"] {
if uptime, err := uptime(); err == nil {
c.uptime = uptime
changed = true
}
}
temp, err := cpuTemp(c.tpath)
if err == nil {
if temp != c.temp {
changed = true
c.temp = temp
c.haveTemp = true
}
}
stats, err := cpuStats()
if err != nil {
log.Printf("unable to read cpu stats: %v", err)
return
}
d := CPUStats{}
total := uint64(0)
for i := 0; i < len(d); i++ {
d[i] = delta(c.stats[i], stats[i])
total += d[i]
}
if total != 0 {
idlePercent := float32((d[3]*10000)/total) / 100
if c.idlePercent != idlePercent {
changed = true
c.idlePercent = idlePercent
}
}
if changed {
fields := []string{}
if c.entities["used_percent"] {
fields = append(fields, fmt.Sprintf(`"idle_percent": %.2f`, c.idlePercent))
}
if c.haveTemp {
fields = append(fields, fmt.Sprintf(`"temperature": %.2f`, float32(c.temp)/1000))
}
if c.entities["uptime"] {
fields = append(fields, fmt.Sprintf(`"uptime": %.2f`, c.uptime))
}
c.msg = "{" + strings.Join(fields, ", ") + "}"
c.Publish()
}
c.stats = stats
}
func delta(old, new uint64) uint64 {
if new <= old {
return 0
}
return new - old
}