Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

A new battery screen #142

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 25 additions & 3 deletions cmd/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ const (
defaultOverallRefreshRate = 1000
defaultConfigFileLocation = ""
defaultCPUBehavior = false
defaultBatteryBehaviour = false
)

var cfgFile string
Expand Down Expand Up @@ -60,9 +61,16 @@ While using a TUI based command, press ? to get information about key bindings (
return err
}

err = systemWideMetricScraper.Serve(factory.WithCPUInfoAs(rootCmd.cpuInfo))
if err != nil && err != core.ErrCanceledByUser {
fmt.Printf("Error: %v\n", err)
if !rootCmd.batteryInfo {
err = systemWideMetricScraper.Serve(factory.WithCPUInfoAs(rootCmd.cpuInfo))
if err != nil && err != core.ErrCanceledByUser {
fmt.Printf("Error: %v\n", err)
}
} else {
err = systemWideMetricScraper.Serve(factory.WithBatteryInfoAs(rootCmd.batteryInfo))
if err != nil && err != core.ErrCanceledByUser {
fmt.Printf("Error: %v\n", err)
}
}

return nil
Expand All @@ -72,6 +80,7 @@ While using a TUI based command, press ? to get information about key bindings (
type rootCommand struct {
refreshRate uint64
cpuInfo bool
batteryInfo bool
}

func constructRootCommand(cmd *cobra.Command, args []string) (*rootCommand, error) {
Expand All @@ -89,9 +98,15 @@ func constructRootCommand(cmd *cobra.Command, args []string) (*rootCommand, erro
return nil, err
}

batteryInfo, err := cmd.Flags().GetBool("battery")
if err != nil {
return nil, err
}

return &rootCommand{
refreshRate: refreshRate,
cpuInfo: cpuInfo,
batteryInfo: batteryInfo,
}, nil
}

Expand Down Expand Up @@ -124,6 +139,13 @@ func init() {
defaultCPUBehavior,
"Info about the CPU Load over all CPUs",
)

rootCmd.Flags().BoolP(
"battery",
"b",
defaultBatteryBehaviour,
"All stats about the battery.",
)
}

// initConfig reads in config file and ENV variables if set.
Expand Down
8 changes: 8 additions & 0 deletions pkg/metrics/factory/options.go
Original file line number Diff line number Diff line change
Expand Up @@ -34,3 +34,11 @@ func WithCPUInfoAs(cpuInfo bool) Option {
swm.cpuInfo = cpuInfo
}
}

// WithBatteryInfoAs sets the battery flag value for the RootCommand.
func WithBatteryInfoAs(batteryInfo bool) Option {
return func(ms MetricScraper) {
swm := ms.(*systemWideMetrics)
swm.batteryInfo = batteryInfo
}
}
29 changes: 29 additions & 0 deletions pkg/metrics/factory/system_wide_metrics.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ import (

type systemWideMetrics struct {
cpuInfo bool
batteryInfo bool
sink core.Sink // defaults to TUI.
refreshRate uint64
}
Expand All @@ -41,6 +42,10 @@ func (swm *systemWideMetrics) Serve(opts ...Option) error {
if swm.cpuInfo {
return swm.serveCPUInfo()
}

if swm.batteryInfo {
return swm.serveBatteryInfo()
}
return swm.serveGenericMetrics()
}

Expand Down Expand Up @@ -91,6 +96,30 @@ func (swm *systemWideMetrics) serveCPUInfo() error {
return eg.Wait()
}

// serveBatteryInfo serves battery stats such as the name of the manufacturer
// and other battery specific information.
func (swm *systemWideMetrics) serveBatteryInfo() error {
eg, ctx := errgroup.WithContext(context.Background())
metricBus := make(chan general.BatteryData, 1)

// start producing metrics.
eg.Go(func() error {
batteryInfo := general.NewBatteryInfo()
alteredRefreshRate := uint64(4 * swm.refreshRate / 5)
return general.GetBatteryInfo(ctx, batteryInfo, metricBus, alteredRefreshRate)
})

// start consuming metrics.
switch swm.sink {
case core.TUI:
eg.Go(func() error {
return overallGraph.RenderBatteryinfo(ctx, metricBus, swm.refreshRate)
})
}

return eg.Wait()
}

// SetSink sets the Sink for the produced metrics.
func (swm *systemWideMetrics) SetSink(sink core.Sink) {
swm.sink = sink
Expand Down
149 changes: 149 additions & 0 deletions pkg/metrics/general/battery_info.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,149 @@
/*
Copyright © 2020 The PES Open Source Team [email protected]

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package general

import (
"bufio"
"context"
"os"
"reflect"
"strings"

"github.com/pesos/grofer/pkg/core"
"github.com/pesos/grofer/pkg/utils"
)

type BatteryInfo struct {
Manufacturer string `json:"manufacturer"`
Technology string `json:"technology"`
ModelName string `json:"model_name"`
SerialNumber string `json:"serial_number"`
Capacity string `json:"capacity"`
CycleCount string `json:"cycle_count"`
EnergyFullDesign string `json:"energy_full_design"`
EnergyFull string `json:"energy_full"`
EnergyNow string `json:"energy_now"`
PowerNow string `json:"power_now"`
Status string `json:"status"`
ChargeStartThreshold string `json:"charge_start_threshold"`
ChargeStopThreshold string `json:"charge_stop_threshold"`
}

type BatteryData struct {
FieldSet string
Battery [][]string
}

// NewBatteryInfo is a constructor for the BatteryInfo type.
func NewBatteryInfo() *BatteryInfo {
return &BatteryInfo{}
}

// GetBatteryInfo updates the BatteryInfo struct and serves the data to the data channel.
func GetBatteryInfo(ctx context.Context, batteryInfo *BatteryInfo, dataChannel chan BatteryData, refreshRate uint64) error {
return utils.TickUntilDone(ctx, refreshRate, func() error {
var batteryFound bool = true
var batteryData BatteryData = BatteryData{
FieldSet: "NO BATTERY DATA",
}
err := batteryInfo.UpdateBatteryInfo()
if err != nil {
if err == core.ErrBatteryNotFound {
batteryFound = false
} else {
return err
}
}

if batteryFound {
batteryData = batteryInfo.getBatteryData()
}

select {
case <-ctx.Done():
return ctx.Err()
case dataChannel <- batteryData:
return nil
}
})
}

// UpdateBatteryInfo updates fields of the type BatteryInfo
func (c *BatteryInfo) UpdateBatteryInfo() error {
err := c.readBatteryInfo()
if err != nil {
return err
}

return nil
}

// ReadBatteryInfo reads files from /sys/class/power_supply/BAT0
// and returns battery specific stats
func (c *BatteryInfo) readBatteryInfo() error {
_, err1 := os.Stat("/sys/class/power_supply/BAT0/manufacturer")
_, err2 := os.Stat("/sys/class/power_supply/BAT0/technology")
_, err3 := os.Stat("/sys/class/power_supply/BAT0/model_name")

if err1 == nil && err2 == nil && err3 == nil {
val := reflect.ValueOf(c).Elem()
for i := 0; i < val.Type().NumField(); i++ {
fileName := val.Type().Field(i).Tag.Get("json")
file, err := os.Open("/sys/class/power_supply/BAT0/" + fileName)
if err != nil {
return err
}
defer file.Close()
reader := bufio.NewReader(file)

// Read first line containing load values
data, err := reader.ReadBytes(byte('\n'))
if err != nil {
return err
}
vals := strings.Fields(string(data))
val.FieldByName(val.Type().Field(i).Name).SetString(vals[0])
}
} else if os.IsNotExist(err1) || os.IsNotExist(err2) || os.IsNotExist(err3) {
return core.ErrBatteryNotFound
}
return nil
}

// getBatteryData structures all the battery stats into the Battery data struct.
func (c *BatteryInfo) getBatteryData() BatteryData {
var bData BatteryData = BatteryData{
FieldSet: "BATTERY",
Battery: [][]string{
{"Stats", "Info"},
{"manufacturer", c.Manufacturer},
{"technology", c.Technology},
{"model name", c.ModelName},
{"serial number", c.SerialNumber},
{"capacity", c.Capacity},
{"cycle count", c.CycleCount},
{"energy full design", c.EnergyFullDesign},
{"energy full", c.EnergyFull},
{"energy now", c.EnergyNow},
{"power now", c.PowerNow},
{"status", c.Status},
{"charge start threshold", c.ChargeStartThreshold},
{"charge stop threshold", c.ChargeStopThreshold},
},
}
return bData
}
45 changes: 45 additions & 0 deletions pkg/sink/tui/general/init.go
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,12 @@ type CPUPage struct {
CPUTable *viz.Table
}

// BatteryPage contains the UI widgets for the UI rendered by the grofer -b command
type BatteryPage struct {
Grid *ui.Grid
Battery *viz.Table
}

// NewPage returns a new page initialized from the MainPage struct
func NewPage(numCores int) *MainPage {
rxSparkLine := viz.NewSparkline()
Expand Down Expand Up @@ -95,6 +101,16 @@ func NewCPUPage(numCores int) *CPUPage {
return page
}

// NewBatteryPage is a constructor for the BatteryPage type
func NewBatteryPage() *BatteryPage {
page := &BatteryPage{
Grid: ui.NewGrid(),
Battery: viz.NewTable(),
}
page.init()
return page
}

// init initializes all ui elements for the ui rendered by the grofer command
func (page *MainPage) init(numCores int) {
if numCores > 8 {
Expand Down Expand Up @@ -424,3 +440,32 @@ func (page *CPUPage) init(numCores int) {
page.Grid.SetRect(0, 0, w, h)

}

func (page *BatteryPage) initBatteryTableWidget() {
page.Battery.Title = " Battery Stats Not Found "
page.Battery.TitleStyle = ui.NewStyle(ui.ColorClear)
page.Battery.BorderStyle.Fg = ui.ColorCyan
page.Battery.HeaderStyle = ui.NewStyle(ui.ColorClear, ui.ColorClear, ui.ModifierBold)
page.Battery.ShowCursor = false
page.Battery.ColResizer = func() {
x := page.Battery.Inner.Dx()
page.Battery.ColWidths = []int{x / 2, x / 2}
}
}

func (page *BatteryPage) initPageGrid() {
page.Grid = ui.NewGrid()
page.Grid.Set(
ui.NewCol(
0.3,
ui.NewRow(0.3, page.Battery),
),
)
w, h := ui.TerminalDimensions()
page.Grid.SetRect(0, 0, w, h)
}

func (page *BatteryPage) init() {
page.initBatteryTableWidget()
page.initPageGrid()
}
Loading