xmtop/widgets/batterygauge.go

87 lines
1.6 KiB
Go
Raw Normal View History

2020-02-19 01:27:29 +08:00
package widgets
import (
"fmt"
"log"
2020-02-19 01:27:29 +08:00
"time"
"github.com/distatus/battery"
"github.com/prometheus/client_golang/prometheus"
2020-04-28 09:33:41 +08:00
"github.com/xxxserxxx/gotop/v4/termui"
2020-02-19 01:27:29 +08:00
)
type BatteryGauge struct {
2020-04-28 09:33:41 +08:00
*termui.Gauge
2020-02-19 01:27:29 +08:00
metric prometheus.Gauge
}
func NewBatteryGauge() *BatteryGauge {
2020-04-28 09:33:41 +08:00
self := &BatteryGauge{Gauge: termui.NewGauge()}
2020-02-19 01:27:29 +08:00
self.Title = " Power Level "
self.update()
go func() {
for range time.NewTicker(time.Second).C {
self.Lock()
self.update()
self.Unlock()
}
}()
return self
}
func (b *BatteryGauge) EnableMetric() {
bats, err := battery.GetAll()
if err != nil {
log.Printf("error setting up metrics: %v", err)
return
}
mx := 0.0
cu := 0.0
for _, bat := range bats {
mx += bat.Full
cu += bat.Current
gauge := prometheus.NewGauge(prometheus.GaugeOpts{
Namespace: "gotop",
Subsystem: "battery",
Name: "total",
})
gauge.Set(cu / mx)
b.metric = gauge
prometheus.MustRegister(gauge)
}
}
2020-04-28 09:33:41 +08:00
func (b *BatteryGauge) update() {
2020-02-19 01:27:29 +08:00
bats, err := battery.GetAll()
if err != nil {
log.Printf("error setting up batteries: %v", err)
2020-02-19 01:27:29 +08:00
return
}
mx := 0.0
cu := 0.0
charging := "%d%% ⚡%s"
rate := 0.0
2020-02-19 01:27:29 +08:00
for _, bat := range bats {
mx += bat.Full
cu += bat.Current
if rate < bat.ChargeRate {
rate = bat.ChargeRate
}
if bat.State == battery.Charging {
charging = "%d%% 🔌%s"
}
2020-02-19 01:27:29 +08:00
}
tn := (mx - cu) / rate
d, _ := time.ParseDuration(fmt.Sprintf("%fh", tn))
2020-04-28 09:33:41 +08:00
b.Percent = int((cu / mx) * 100.0)
b.Label = fmt.Sprintf(charging, b.Percent, d.Truncate(time.Minute))
if b.metric != nil {
b.metric.Set(cu / mx)
2020-02-19 01:27:29 +08:00
}
}