-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
125 lines (108 loc) · 2.34 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
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
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
package main
import (
"container/list"
"flag"
"fmt"
"os"
"os/signal"
"syscall"
"time"
. "github.com/sav/uap/lib"
)
type Monitor func(*Config, *list.List)
type Status func(*Config, *list.List)
func start(
config *Config,
monitor Monitor,
status Status,
) {
tick := time.Tick(1500 * time.Millisecond)
sigs := make(chan os.Signal, 1)
signal.Notify(sigs, []os.Signal{
syscall.SIGINT,
syscall.SIGTERM,
syscall.SIGUSR1,
}...)
bats, err := GetBatteries()
if err != nil {
Log.Err("Could not get battery info: %v", err)
os.Exit(1)
}
Log.Dbg("Starting UAP...")
status(config, bats)
var quit = false
for !quit {
select {
case <-tick:
monitor(config, bats)
case sig := <-sigs:
if sig == syscall.SIGUSR1 {
status(config, bats)
} else {
Log.Dbg("Received signal: %v", sig)
quit = true
}
default:
time.Sleep(500 * time.Millisecond)
}
}
}
func monitor(config *Config, batteries *list.List) {
Update(batteries, func(event Event) {
switch event.Kind {
case Added:
Log.Info("%v: ☑ (Added)", event.Battery.Name)
Log.Info("%v", event.Battery)
case Removed:
Log.Info("%v: ☒ (Removed)", event.Battery.Name)
default:
Log.Info("%v", event.Battery)
}
// Don't reset when state's changing to either Charging or Removed.
AlertSet(config, event.Battery,
event.Kind == Charging || event.Kind == Removed)
AlertEvent(config, &event)
})
ListMap(batteries, func(battery *Battery) {
AlertIfCritical(config, battery)
})
}
func status(_ *Config, batteries *list.List) {
if batteries.Len() == 0 {
Log.Info("No batteries found.")
}
ListMap(batteries, func(battery *Battery) {
Log.Info("%v", battery)
})
}
var (
config Config
configFile string
logFile string
verbose bool
)
func init() {
flag.StringVar(&configFile, "c", DefaultConfig(),
"Load configuration from file.")
flag.StringVar(&logFile, "l", "", "Write logs to file.")
flag.BoolVar(&verbose, "v", false, "Enable verbose output.")
}
func main() {
flag.Parse()
config, err := LoadConfig(configFile)
if err != nil {
fmt.Fprintf(os.Stderr, "Error: %s\n", err)
config = Config{}
}
err = nil
if logFile != "" {
err = SetLogFile(logFile)
} else if config.LogFile != "" {
err = SetLogFile(config.LogFile)
}
if err != nil {
panic(err)
}
SetLogDebug(verbose || config.Verbose)
start(&config, monitor, status)
}