summaryrefslogtreecommitdiffstats
path: root/widgets/battery.go
blob: d8334bb41d706f387194b87ea1f59dc20f69e672 (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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
package widgets

import (
	"fmt"
	"log"
	"math"
	"strconv"
	"time"

	"github.com/VictoriaMetrics/metrics"
	"github.com/distatus/battery"

	ui "github.com/xxxserxxx/gotop/v4/termui"
)

type BatteryWidget struct {
	*ui.LineGraph
	updateInterval time.Duration
}

func NewBatteryWidget(horizontalScale int) *BatteryWidget {
	self := &BatteryWidget{
		LineGraph:      ui.NewLineGraph(),
		updateInterval: time.Minute,
	}
	self.Title = tr.Value("widget.label.battery")
	self.HorizontalScale = horizontalScale

	// intentional duplicate
	// adds 2 datapoints to the graph, otherwise the dot is difficult to see
	self.update()
	self.update()

	go func() {
		for range time.NewTicker(self.updateInterval).C {
			self.Lock()
			self.update()
			self.Unlock()
		}
	}()

	return self
}

func (b *BatteryWidget) EnableMetric() {
	bats, err := battery.GetAll()
	if err != nil {
		log.Printf(tr.Value("error.metricsetup", "batt", err.Error()))
		return
	}
	for i, _ := range bats {
		id := makeID(i)
		metrics.NewGauge(makeName("battery", i), func() float64 {
			if ds, ok := b.Data[id]; ok {
				return ds[len(ds)-1]
			}
			return 0.0
		})
	}
}

func makeID(i int) string {
	return tr.Value("widget.label.batt") + strconv.Itoa(i)
}

func (b *BatteryWidget) Scale(i int) {
	b.LineGraph.HorizontalScale = i
}

func (b *BatteryWidget) update() {
	batteries, err := battery.GetAll()
	if err != nil {
		switch errt := err.(type) {
		case battery.ErrFatal:
			log.Printf(tr.Value("error.fatalfetch", "batt", err.Error()))
			return
		case battery.Errors:
			batts := make([]*battery.Battery, 0)
			for i, e := range errt {
				if e == nil {
					batts = append(batts, batteries[i])
				} else {
					log.Printf(tr.Value("error.recovfetch"), "batt", e.Error())
				}
			}
			if len(batts) < 1 {
				log.Print(tr.Value("error.nodevfound", "batt"))
				return
			}
			batteries = batts
		}
	}
	for i, battery := range batteries {
		id := makeID(i)
		perc := battery.Current / battery.Full
		percentFull := math.Abs(perc) * 100.0
		// TODO: look into this sort of thing; doesn't the array grow forever? Is the widget library truncating it?
		b.Data[id] = append(b.Data[id], percentFull)
		b.Labels[id] = fmt.Sprintf("%3.0f%% %.0f/%.0f", percentFull, math.Abs(battery.Current), math.Abs(battery.Full))
	}
}