summaryrefslogtreecommitdiffstats
path: root/widgets/battery.go
blob: 89620bbe28ae0f3462c862d2e4724872897459e7 (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
package widgets

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

	"github.com/distatus/battery"

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

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

func NewBatteryWidget(horizontalScale int) *BatteryWidget {
	self := &BatteryWidget{
		LineGraph:      ui.NewLineGraph(),
		updateInterval: time.Minute,
	}
	self.Title = " Battery Status "
	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 makeId(i int) string {
	return "Batt" + strconv.Itoa(i)
}

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

func (self *BatteryWidget) update() {
	batteries, err := battery.GetAll()
	if err != nil {
		log.Printf("failed to get battery info: %v", err)
		return
	}
	for i, battery := range batteries {
		id := makeId(i)
		percentFull := math.Abs(battery.Current/battery.Full) * 100.0
		self.Data[id] = append(self.Data[id], percentFull)
		self.Labels[id] = fmt.Sprintf("%3.0f%% %.0f/%.0f", percentFull, math.Abs(battery.Current), math.Abs(battery.Full))
	}
}