xmtop/src/widgets/battery.go

62 lines
1.3 KiB
Go
Raw Normal View History

package widgets
import (
"fmt"
"log"
"math"
"strconv"
"sync"
"time"
"github.com/distatus/battery"
2019-01-31 07:20:09 +08:00
ui "github.com/cjbassi/gotop/src/termui"
)
2019-03-01 08:29:52 +08:00
type BatteryWidget struct {
*ui.LineGraph
2019-03-01 08:29:52 +08:00
updateInterval time.Duration
}
2019-03-01 08:29:52 +08:00
func NewBatteryWidget(renderLock *sync.RWMutex, horizontalScale int) *BatteryWidget {
self := &BatteryWidget{
LineGraph: ui.NewLineGraph(),
updateInterval: time.Minute,
}
2019-01-31 07:20:09 +08:00
self.Title = " Battery Status "
2019-01-13 08:31:37 +08:00
self.HorizontalScale = horizontalScale
2019-01-31 07:20:09 +08:00
// intentional duplicate
2019-03-01 08:29:52 +08:00
// adds 2 datapoints to the graph, otherwise the dot is difficult to see
2019-01-31 07:20:09 +08:00
self.update()
self.update()
go func() {
2019-03-01 08:29:52 +08:00
for range time.NewTicker(self.updateInterval).C {
renderLock.RLock()
self.update()
renderLock.RUnlock()
}
}()
return self
}
2019-03-01 08:29:52 +08:00
func makeId(i int) string {
return "Batt" + strconv.Itoa(i)
}
2019-03-01 08:29:52 +08:00
func (self *BatteryWidget) update() {
batteries, err := battery.GetAll()
if err != nil {
2019-03-01 08:29:52 +08:00
log.Printf("failed to get battery info: %v", err)
2019-01-31 07:20:09 +08:00
return
}
2019-03-01 08:29:52 +08:00
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))
}
}