2018-12-27 12:06:55 +08:00
|
|
|
package widgets
|
|
|
|
|
|
|
|
import (
|
|
|
|
"fmt"
|
|
|
|
"log"
|
|
|
|
"math"
|
|
|
|
"strconv"
|
2019-01-20 12:34:19 +08:00
|
|
|
"sync"
|
2018-12-27 12:06:55 +08:00
|
|
|
"time"
|
|
|
|
|
2019-02-16 20:12:52 +08:00
|
|
|
"github.com/distatus/battery"
|
2019-01-31 07:20:09 +08:00
|
|
|
|
|
|
|
ui "github.com/cjbassi/gotop/src/termui"
|
2018-12-27 12:06:55 +08:00
|
|
|
)
|
|
|
|
|
2019-03-01 08:29:52 +08:00
|
|
|
type BatteryWidget struct {
|
2018-12-27 12:06:55 +08:00
|
|
|
*ui.LineGraph
|
2019-03-01 08:29:52 +08:00
|
|
|
updateInterval time.Duration
|
2018-12-27 12:06:55 +08:00
|
|
|
}
|
|
|
|
|
2019-03-01 08:29:52 +08:00
|
|
|
func NewBatteryWidget(renderLock *sync.RWMutex, horizontalScale int) *BatteryWidget {
|
|
|
|
self := &BatteryWidget{
|
|
|
|
LineGraph: ui.NewLineGraph(),
|
|
|
|
updateInterval: time.Minute,
|
2018-12-27 12:06:55 +08:00
|
|
|
}
|
2019-01-31 07:20:09 +08:00
|
|
|
self.Title = " Battery Status "
|
2019-01-13 08:31:37 +08:00
|
|
|
self.HorizontalScale = horizontalScale
|
2018-12-27 12:06:55 +08:00
|
|
|
|
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()
|
2018-12-27 12:06:55 +08:00
|
|
|
self.update()
|
|
|
|
|
|
|
|
go func() {
|
2019-03-01 08:29:52 +08:00
|
|
|
for range time.NewTicker(self.updateInterval).C {
|
2019-01-20 12:34:19 +08:00
|
|
|
renderLock.RLock()
|
2018-12-27 12:06:55 +08:00
|
|
|
self.update()
|
2019-01-20 12:34:19 +08:00
|
|
|
renderLock.RUnlock()
|
2018-12-27 12:06:55 +08:00
|
|
|
}
|
|
|
|
}()
|
|
|
|
|
|
|
|
return self
|
|
|
|
}
|
|
|
|
|
2019-03-01 08:29:52 +08:00
|
|
|
func makeId(i int) string {
|
2018-12-27 12:06:55 +08:00
|
|
|
return "Batt" + strconv.Itoa(i)
|
|
|
|
}
|
|
|
|
|
2019-03-01 08:29:52 +08:00
|
|
|
func (self *BatteryWidget) update() {
|
|
|
|
batteries, err := battery.GetAll()
|
2018-12-27 12:06:55 +08:00
|
|
|
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
|
2018-12-27 12:06:55 +08:00
|
|
|
}
|
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))
|
2018-12-27 12:06:55 +08:00
|
|
|
}
|
|
|
|
}
|