-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
78 lines (63 loc) · 1.86 KB
/
main.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
package main
import (
"flag"
"fmt"
"math"
"os"
"strings"
)
const defaultFmtStr = "{capacity}% - {usage}W - {H}h {M}m"
var Version = "localdev"
func main() {
fs := flag.NewFlagSet(fmt.Sprintf("Powerbar %s", Version), flag.ExitOnError)
dischargeStr := fs.String("discharging", defaultFmtStr, "format string")
chargeStr := fs.String("charging", defaultFmtStr, "format string")
fullStr := fs.String("full", defaultFmtStr, "format string")
waybarMode := fs.Bool("waybar", false, "enable waybar mode")
if err := fs.Parse(os.Args[1:]); err != nil {
fs.Usage()
os.Exit(-1)
}
pc, err := NewPowerClient()
if err != nil {
fmt.Fprintf(os.Stderr, "could not create dbus conn: %v\n", err)
os.Exit(-1)
}
bs, err := pc.GetBatteryStatus()
if err != nil {
fmt.Fprintf(os.Stderr, "could not get battery status: %v\n", err)
os.Exit(-1)
}
fmtStr := *dischargeStr
if bs.IsCharging && bs.Capacity > 99 {
fmtStr = *fullStr
} else if bs.IsCharging {
fmtStr = *chargeStr
}
if *waybarMode {
fmt.Fprintf(os.Stdout,
`{"text":"%s","percentage":%1f,"class":"%s"}\n`,
applyFmt(fmtStr, bs),
bs.Capacity,
strings.ReplaceAll(strings.ToLower(bs.State.String()), " ", "-"))
} else {
fmt.Fprintln(os.Stdout, applyFmt(fmtStr, bs))
}
}
func applyFmt(str string, bs BatteryStatus) string {
result := strings.ReplaceAll(str, "{capacity}", fmt.Sprintf("%.0f", bs.Capacity))
eta := bs.TimeUntilEmpty
if bs.IsCharging {
eta = bs.TimeUntilFull
}
hours := math.Floor(eta.Hours())
mins := "0"
if eta.Minutes() >= 1 {
mins = fmt.Sprintf("%1.0f", eta.Minutes()-(hours*60))
}
result = strings.ReplaceAll(result, "{H}", fmt.Sprintf("%1.0f", hours))
result = strings.ReplaceAll(result, "{M}", mins)
result = strings.ReplaceAll(result, "{usage}", fmt.Sprintf("%.2f", bs.Usage))
result = strings.ReplaceAll(result, "{state}", fmt.Sprintf("%s", bs.State))
return result
}