-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathbattery.go
107 lines (90 loc) · 1.96 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
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
package main
import (
"bufio"
"os"
"strconv"
"strings"
)
type Status uint8
const (
UNKNOWN Status = 0
CHARGING Status = 1
DISCHARGING Status = 2
NOT_CHARGING Status = 3
FULL Status = 4
)
type Battery struct {
Name string
ModelName string
Technology string
Capacity int
Status Status
}
func (battery *Battery) Charging() bool {
return battery.Status == FULL || battery.Status == CHARGING
}
func parseStatus(value string) Status {
switch value {
case "Charging":
return CHARGING
case "Discharging":
return DISCHARGING
case "Not charging":
return NOT_CHARGING
case "Full":
return FULL
default:
return UNKNOWN
}
}
func load(path string) ([]string, error) {
file, err := os.Open(path)
if err != nil {
return nil, err
}
defer file.Close()
var lines []string
scanner := bufio.NewScanner(file)
for scanner.Scan() {
lines = append(lines, scanner.Text())
}
return lines, scanner.Err()
}
func parse(content []string) map[string]string {
info := make(map[string]string)
for _, line := range content {
tokens := strings.SplitN(line, "=", 2)
if len(tokens) != 2 {
continue
}
key, value := tokens[0], tokens[1]
info[key] = value
}
return info
}
func build(info map[string]string) (*Battery, error) {
capacity, err := strconv.Atoi(info["POWER_SUPPLY_CAPACITY"])
if err != nil {
return nil, err
}
return &Battery{
Name: info["POWER_SUPPLY_NAME"],
Capacity: capacity,
ModelName: info["POWER_SUPPLY_MODEL_NAME"],
Status: parseStatus(info["POWER_SUPPLY_STATUS"]),
Technology: info["POWER_SUPPLY_TECHNOLOGY"],
}, nil
}
func LoadBatteryInfo(uevent string) (*Battery, error) {
content, err := load(uevent)
if err != nil {
logError("ERROR: Could not load battery file '%s'.", uevent)
return nil, err
}
battery, err := build(parse(content))
if err != nil {
logError("Could not parse 'POWER_SUPPLY_CAPACITY' from battery file '%s'.", uevent)
return nil, err
}
return battery, nil
}