xmtop/src/widgets/battery.go

61 lines
1.1 KiB
Go
Raw Normal View History

package widgets
import (
"fmt"
"log"
"math"
"strconv"
"sync"
"time"
"github.com/cjbassi/battery"
2019-01-31 07:20:09 +08:00
ui "github.com/cjbassi/gotop/src/termui"
)
type Batt struct {
*ui.LineGraph
interval time.Duration
}
func NewBatt(renderLock *sync.RWMutex, horizontalScale int) *Batt {
self := &Batt{
LineGraph: ui.NewLineGraph(),
2019-01-20 11:37:31 +08:00
interval: 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
self.update()
self.update()
go func() {
2019-01-31 07:20:09 +08:00
for range time.NewTicker(self.interval).C {
renderLock.RLock()
self.update()
renderLock.RUnlock()
}
}()
return self
}
func mkId(i int) string {
return "Batt" + strconv.Itoa(i)
}
func (self *Batt) update() {
batts, err := battery.GetAll()
if err != nil {
log.Printf("failed to get battery info from system: %v", err)
2019-01-31 07:20:09 +08:00
return
}
for i, b := range batts {
n := mkId(i)
pc := math.Abs(b.Current/b.Full) * 100.0
self.Data[n] = append(self.Data[n], pc)
self.Labels[n] = fmt.Sprintf("%3.0f%% %.0f/%.0f", pc, math.Abs(b.Current), math.Abs(b.Full))
}
}