xmtop/widgets/batterygauge.go

73 lines
1.3 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/VictoriaMetrics/metrics"
2020-02-19 01:27:29 +08:00
"github.com/distatus/battery"
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
}
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() {
metrics.NewGauge(makeName("battery", "total"), func() float64 {
return float64(b.Percent)
})
2020-02-19 01:27:29 +08:00
}
// Only report battery errors once.
var errLogged = false
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 {
if !errLogged {
log.Printf("error setting up batteries: %v", err)
errLogged = true
}
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))
2020-02-19 01:27:29 +08:00
}