-
-
Notifications
You must be signed in to change notification settings - Fork 2
/
power.go
132 lines (111 loc) · 2.21 KB
/
power.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
package main
import (
"fmt"
"log"
"os"
"path/filepath"
"strconv"
"strings"
"time"
)
type pw_sources struct {
AC string
val string
batteries []string
}
func (s *pw_sources) value() string {
return s.val
}
func power() element {
e := &pw_sources{}
if err := e.prepare(); err != nil {
log.Printf("failed to prepare battery: %v\n", err)
return e
}
go func() {
for {
e.val = e.read()
time.Sleep(time.Second * 3)
}
}()
return e
}
func (s *pw_sources) prepare() error {
devs, err := os.ReadDir("/sys/class/power_supply")
if err != nil {
return err
}
for _, dev := range devs {
d := filepath.Base(dev.Name())
p := filepath.Join("/sys/class/power_supply", d)
// filter out non devices
if !file_exists(filepath.Join(p, "device")) {
continue // not a physical device
}
// maybe battery
if strings.Index(d, "BAT") != -1 {
cap := filepath.Join(p, "capacity")
if !file_exists(cap) {
return fmt.Errorf("could not locate battery capacity stats at: %s", cap)
}
s.batteries = append(s.batteries, cap)
}
if d == "AC" {
s.AC = filepath.Join(p, "online")
if !file_exists(s.AC) {
return fmt.Errorf("could not locate AC online stat at: %s", s.AC)
}
}
}
return nil
}
func (s *pw_sources) onAC() bool {
if len(s.batteries) == 0 {
return true
}
if len(s.AC) == 0 {
return false // should not be the case
}
dat, err := os.ReadFile(s.AC)
if err != nil {
return false
}
if strings.TrimSpace(string(dat)) == "0" {
return false
}
return true
}
func (s *pw_sources) battery() int {
if len(s.batteries) == 0 {
return 0 // no baterries
}
var all int
for _, b := range s.batteries {
dat, err := os.ReadFile(b)
if err != nil {
continue
}
i, _ := strconv.Atoi(strings.TrimSpace(string(dat)))
all += i
}
return all / len(s.batteries)
}
func (s *pw_sources) read() string {
if s.onAC() {
return "^i(" + xbm("power-ac") + ")"
}
perc := s.battery()
var color, icon string
switch {
case perc <= 20:
icon = xbm("bat-low")
color = "#dc322f"
case perc <= 50:
icon = xbm("bat-mid")
color = "#b58900"
default:
icon = xbm("bat-full")
color = "#859900"
}
return fmt.Sprintf("^fg(%s)%d%%^i(%s)^fg()", color, perc, icon)
}