forked from creativeprojects/resticprofile
-
Notifications
You must be signed in to change notification settings - Fork 0
/
battery.go
85 lines (75 loc) · 1.97 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
package main
import (
"math"
"github.com/creativeprojects/clog"
"github.com/distatus/battery"
)
// IsRunningOnBattery returns true if the computer is running on battery,
// followed by the percentage of battery remaining. If no battery is present
// the percentage will be 0.
func IsRunningOnBattery() (bool, int, error) {
batteries, err := battery.GetAll()
if err != nil {
err = isFatalError(err)
if err != nil {
return false, 0, err
}
}
if len(batteries) == 0 {
clog.Debug("no battery detected")
return false, 0, nil
}
return detectRunningOnBattery(batteries),
int(math.Round(averageBatteryLevel(batteries))), nil
}
// isFatalError returns an error if we can't detect any battery state
func isFatalError(err error) error {
switch perr := err.(type) {
case battery.ErrFatal: // complete failure
return err
case battery.Errors: // range of errors per battery
for _, err := range perr {
if err != nil {
err = isFatalError(err)
if err != nil {
return err
}
}
}
return nil
case battery.ErrPartial: // only some errors on one battery
if perr.State != nil {
return perr.State
}
// we're only interested in the state
return nil
}
return err
}
// detectRunningOnBattery returns true if all batteries are discharging
func detectRunningOnBattery(batteries []*battery.Battery) bool {
pluggedIn := false
discharging := false
for _, bat := range batteries {
if bat.State.Raw == battery.Discharging || bat.State.Raw == battery.Empty {
discharging = true
} else if bat.State.Raw == battery.Charging || bat.State.Raw == battery.Full || bat.State.Raw == battery.Idle || bat.State.Raw == battery.Unknown {
pluggedIn = true
}
}
return !pluggedIn && discharging
}
func averageBatteryLevel(batteries []*battery.Battery) float64 {
var total, count float64
for _, bat := range batteries {
if bat.Full <= 0 {
continue
}
count++
total += bat.Current * 100 / bat.Full
}
if count == 0 {
return 0
}
return total / count
}