-
Notifications
You must be signed in to change notification settings - Fork 12
/
battery.go
110 lines (98 loc) · 2.6 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
108
109
110
package androidutils
import (
"fmt"
"os/exec"
"regexp"
)
// ref: http://android-test-tw.blogspot.jp/2012/10/dumpsys-information-android-open-source.html
const (
BatteryStatusUnknown = 1
BatteryStatusCharging = 2
BatteryStatusDischarging = 3
BatteryStatusNotCharging = 4
BatteryStatusFull = 5
BatteryHealthUnknown = 1
BatteryHealthGood = 2
BatteryHealthOverheat = 3
BatteryHealthDead = 4
BatteryHealthOverVoltage = 5
BatteryHealthUnspecifiedFailure = 6
BatteryHealthCold = 7
)
type Battery struct {
ACPowered bool `json:"acPowered"`
USBPowered bool `json:"usbPowered"`
WirelessPowered bool `json:"wirelessPowered"`
Status int `json:"status"`
Health int `json:"health"`
Present bool `json:"present"`
Level int `json:"level"`
Scale int `json:"scale"`
Voltage int `json:"voltage"`
Temperature int `json:"temperature"`
Technology string `json:"technology"`
}
func (self *Battery) StatusName() string {
var ss = []string{"unknown", "charging", "discharging", "notcharging", "full"}
if self.Status < 1 || self.Status > 5 {
return "unknown"
}
return ss[self.Status-1]
}
func dumpsysCommand(args ...string) ([]byte, error) {
cmd := exec.Command("dumpsys")
cmd.Args = append(cmd.Args, args...)
return cmd.Output()
}
func parseBool(s string) bool {
return s == "true"
}
func parseInt(s string) int {
var a int
fmt.Sscanf(s, "%d", &a)
return a
}
func (self *Battery) Update() error {
out, err := dumpsysCommand("battery")
if err != nil {
return err
}
//log.Println(string(out))
patten := regexp.MustCompile(`(\w+[\w ]*\w+):\s*([-\w\d]+)(\r|\n)`)
ms := patten.FindAllStringSubmatch(string(out), -1)
exists := make(map[string]bool)
for _, fields := range ms {
var key, val = fields[1], fields[2]
// filter duplicate items.
// will happen on phone: 红米Note3
if exists[key] {
continue
}
exists[key] = true
switch key {
case "AC powered":
self.ACPowered = parseBool(val)
case "USB powered":
self.USBPowered = parseBool(val)
case "Wireless powered":
self.WirelessPowered = parseBool(val)
case "status":
self.Status = parseInt(val)
case "health":
self.Health = parseInt(val)
case "present":
self.Present = parseBool(val)
case "level":
self.Level = parseInt(val)
case "scale":
self.Scale = parseInt(val)
case "voltage":
self.Voltage = parseInt(val)
case "temperature":
self.Temperature = parseInt(val)
case "technology":
self.Technology = val
}
}
return nil
}