hbspbar

bspwm status bar
git clone https://hhvn.uk/hbspbar
git clone git://hhvn.uk/hbspbar
Log | Files | Refs

01-bat.go (1781B)


      1 package status // import "hhvn.uk/hbspbar/status"
      2 
      3 import (
      4 	"os"
      5 	"path"
      6 	"errors"
      7 	"strings"
      8 	"image/color"
      9 
     10 	// "hhvn.uk/hbspbar/drw"
     11 	"hhvn.uk/hbspbar/config"
     12 	"hhvn.uk/hbspbar/common"
     13 )
     14 
     15 func bat(u *Block) error {
     16 	dir := "/sys/class/power_supply"
     17 
     18 	const (
     19 		nothing = iota
     20 		charging
     21 		discharging
     22 	)
     23 
     24 	dirs, err := os.ReadDir(dir)
     25 	if dirs == nil { return err }
     26 
     27 	totalcap := 0
     28 	usedcap := 0
     29 
     30 	stati := nothing
     31 
     32 	for _, d := range dirs {
     33 		if !strings.HasPrefix(d.Name(), "BAT") { continue }
     34 		
     35 		caps, err := common.FileAsLines(path.Join(dir, d.Name(), "capacity"))
     36 		if err != nil { return err }
     37 
     38 		capi, err := common.Intify(caps[0])
     39 		if err != nil { return err }
     40 
     41 		totalcap += 100
     42 		usedcap += capi
     43 
     44 		stats, err := common.FileAsLines(path.Join(dir, d.Name(), "status"))
     45 		if err != nil { return err }
     46 
     47 		// Doesn't deal with 1 battery charging, and another discharging but w/e
     48 		switch stats[0] {
     49 		case "Charging": if charging > stati { stati = charging }
     50 		case "Discharging": if discharging > stati { stati = discharging}
     51 		}
     52 	}
     53 
     54 	if totalcap == 0 {
     55 		return errors.New("no batteries")
     56 	}
     57 
     58 	avgcap := (usedcap * 100) / totalcap
     59 
     60 	var c color.Color
     61 
     62 	// Colour of outline = charge indicator
     63 	switch stati {
     64 	case nothing:     c = config.Fg
     65 	case charging:    c = config.Green
     66 	case discharging: c = config.Red
     67 	}
     68 
     69 	var iw int = 20
     70 	var ih int = int(config.H) - 8
     71 	var w  int = iw * avgcap / 100
     72 
     73 	// Draw nose
     74 	u.drawRect(2, int((config.H - 5) / 2), 2, 5, c, true)
     75 
     76 	// Draw border
     77 	u.drawRect(4, 3, iw + 2, ih + 2, c, false)
     78 
     79 	switch {
     80 	case avgcap < 25:  c = config.Red
     81 	case avgcap >= 99: c = config.Green
     82 	default:           c = config.FgDark
     83 	}
     84 
     85 	// Fill
     86 	u.drawRect(4 + iw - w, 4, w + 1, ih, c, true)
     87 
     88 	return nil
     89 }
     90 
     91 func init() {
     92 	register("bat", bat, 1)
     93 }