-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
147 lines (124 loc) · 2.55 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
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
package main
import (
"context"
_ "embed"
"log"
"os/exec"
"strings"
"time"
"github.com/endocrimes/keylight-go"
"github.com/getlantern/systray"
)
var (
//go:embed icon/elgatoicon.png
icon []byte
)
func main() {
systray.Run(onReady, nil)
}
func discoverLights() (<-chan *keylight.Device, error) {
discovery, err := keylight.NewDiscovery()
if err != nil {
log.Println("failed to initialize keylight discovery: ", err.Error())
return nil, err
}
go func() {
err := discovery.Run(context.Background())
if err != nil {
log.Fatalln("Failed to discover lights: ", err.Error())
}
}()
return discovery.ResultsCh(), nil
}
func isLightOn(state int) bool {
if state == 0 {
return true
}
return false
}
func togglePowerState(lg *keylight.LightGroup) *keylight.LightGroup {
newLG := lg.Copy()
for i, l := range lg.Lights {
if isLightOn(l.On) {
newLG.Lights[i].On = 1
} else {
newLG.Lights[i].On = 0
}
}
return newLG
}
func writeDiscoverConfig() error {
timeout := time.Duration(5 * time.Second)
devicesCh, err := discoverLights()
if err != nil {
return err
}
count := 0
var allLights []*keylight.Device
dAllLights := systray.AddMenuItem("Power Toggle All", "")
dAllLights.Enable()
systray.AddSeparator()
go func(dAllLights *systray.MenuItem) {
for {
_, ok := <-dAllLights.ClickedCh
if !ok {
break
}
for _, d := range allLights {
lg, _ := d.FetchLightGroup(context.TODO())
d.UpdateLightGroup(context.TODO(), togglePowerState(lg))
}
}
}(dAllLights)
loop:
for {
select {
case device := <-devicesCh:
if device == nil {
break loop
}
allLights = append(allLights, device)
dName := systray.AddMenuItem(strings.ReplaceAll(device.Name, `\`, ""), "")
dName.Enable()
go func(dName *systray.MenuItem) {
for {
_, ok := <-dName.ClickedCh
if !ok {
break
}
lg, _ := device.FetchLightGroup(context.TODO())
device.UpdateLightGroup(context.TODO(), togglePowerState(lg))
}
}(dName)
count++
case <-time.After(timeout):
break loop
}
}
systray.AddSeparator()
settings := systray.AddMenuItem("Settings", "")
settings.Enable()
go func(settings *systray.MenuItem) {
for {
_, ok := <-settings.ClickedCh
if !ok {
break
}
cmd := exec.Command("keylight-control")
err := cmd.Run()
if err != nil {
log.Printf("Error: %v", err)
}
}
}(settings)
return nil
}
func onReady() {
systray.SetIcon(icon)
writeDiscoverConfig()
mExit := systray.AddMenuItem("Exit", "")
go func() {
<-mExit.ClickedCh
systray.Quit()
}()
}