-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathbattery.go
60 lines (50 loc) · 1.28 KB
/
battery.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
package main
import (
"bufio"
"os"
"strconv"
"strings"
karma "github.com/reconquest/karma-go"
)
func GetBatteryInfo(uevent string) (int, bool, error) {
file, err := os.Open(uevent)
if err != nil {
return 0, false, karma.Format(
err,
"unable to open uevent file: %s",
uevent,
)
}
defer file.Close()
scanner := bufio.NewScanner(file)
var full, fullDesign, now float64
var present bool
for scanner.Scan() {
tokens := strings.SplitN(scanner.Text(), "=", 2)
if len(tokens) != 2 {
continue
}
switch tokens[0] {
case "POWER_SUPPLY_CHARGE_FULL_DESIGN":
fullDesign, _ = strconv.ParseFloat(tokens[1], 64)
case "POWER_SUPPLY_ENERGY_FULL_DESIGN":
fullDesign, _ = strconv.ParseFloat(tokens[1], 64)
case "POWER_SUPPLY_CHARGE_FULL":
full, _ = strconv.ParseFloat(tokens[1], 64)
case "POWER_SUPPLY_ENERGY_FULL":
full, _ = strconv.ParseFloat(tokens[1], 64)
case "POWER_SUPPLY_ENERGY_NOW":
now, _ = strconv.ParseFloat(tokens[1], 64)
case "POWER_SUPPLY_CHARGE_NOW":
now, _ = strconv.ParseFloat(tokens[1], 64)
case "POWER_SUPPLY_STATUS":
present = tokens[1] != "Discharging"
}
}
// Sometimes it happens for laptops
if fullDesign > full && now > full {
full = fullDesign
}
percentage := int(now / full * 100)
return percentage, present, nil
}