summaryrefslogtreecommitdiffstats
path: root/widgets/batterygauge.go
blob: 534c1cf43e72938eab1f4c5fc419e223cdd6aaaa (plain)
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
package widgets

import (
	"fmt"
	"log"

	"time"

	"github.com/distatus/battery"
	"github.com/prometheus/client_golang/prometheus"

	. "github.com/xxxserxxx/gotop/v3/termui"
)

type BatteryGauge struct {
	*Gauge
	metric prometheus.Gauge
}

func NewBatteryGauge() *BatteryGauge {
	self := &BatteryGauge{Gauge: NewGauge()}
	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)
	}
}

func (self *BatteryGauge) update() {
	bats, err := battery.GetAll()
	if err != nil {
		log.Printf("error setting up batteries: %v", err)
		return
	}
	mx := 0.0
	cu := 0.0
	charging := "%d%% ⚡%s"
	rate := 0.0
	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"
		}
	}
	tn := (mx - cu) / rate
	d, _ := time.ParseDuration(fmt.Sprintf("%fh", tn))
	self.Percent = int((cu / mx) * 100.0)
	self.Label = fmt.Sprintf(charging, self.Percent, d.Truncate(time.Minute))
	if self.metric != nil {
		self.metric.Set(cu / mx)
	}
}