xmtop/widgets/temp.go

85 lines
1.6 KiB
Go
Raw Normal View History

2018-02-19 15:25:02 +08:00
package widgets
// Temp is too customized to inherit from a generic widget so we create a customized one here.
// Temp defines its own Buffer method directly.
2018-02-19 15:25:02 +08:00
import (
"fmt"
2018-03-04 09:05:52 +08:00
"sort"
2018-02-19 15:25:02 +08:00
"strings"
"time"
ui "github.com/cjbassi/gotop/termui"
2018-03-04 09:05:52 +08:00
psHost "github.com/shirou/gopsutil/host"
2018-02-19 15:25:02 +08:00
)
type Temp struct {
*ui.Block
2018-03-04 09:05:52 +08:00
interval time.Duration
Data map[string]int
Threshold int
TempLow ui.Color
TempHigh ui.Color
2018-02-19 15:25:02 +08:00
}
func NewTemp() *Temp {
t := &Temp{
Block: ui.NewBlock(),
interval: time.Second * 5,
2018-03-04 09:05:52 +08:00
Data: make(map[string]int),
Threshold: 80, // temp at which color should change
}
2018-02-19 15:25:02 +08:00
t.Label = "Temperatures"
go t.update()
ticker := time.NewTicker(t.interval)
go func() {
for range ticker.C {
t.update()
}
}()
return t
}
func (t *Temp) update() {
2018-03-04 09:05:52 +08:00
sensors, _ := psHost.SensorsTemperatures()
for _, sensor := range sensors {
2018-02-19 15:25:02 +08:00
// only sensors with input in their name are giving us live temp info
2018-03-04 09:05:52 +08:00
if strings.Contains(sensor.SensorKey, "input") {
2018-02-19 15:25:02 +08:00
// removes '_input' from the end of the sensor name
2018-03-04 09:05:52 +08:00
label := sensor.SensorKey[:strings.Index(sensor.SensorKey, "_input")]
t.Data[label] = int(sensor.Temperature)
2018-02-19 15:25:02 +08:00
}
}
}
// Buffer implements ui.Bufferer interface.
func (t *Temp) Buffer() *ui.Buffer {
buf := t.Block.Buffer()
2018-03-04 09:05:52 +08:00
var keys []string
for k := range t.Data {
keys = append(keys, k)
}
sort.Strings(keys)
for y, key := range keys {
if y+1 > t.Y {
break
}
fg := t.TempLow
2018-03-04 09:05:52 +08:00
if t.Data[key] >= t.Threshold {
fg = t.TempHigh
}
2018-03-04 09:05:52 +08:00
s := ui.MaxString(key, (t.X - 4))
buf.SetString(1, y+1, s, t.Fg, t.Bg)
2018-03-04 09:05:52 +08:00
buf.SetString(t.X-2, y+1, fmt.Sprintf("%dC", t.Data[key]), fg, t.Bg)
}
return buf
}