/
yeego.go
288 lines (259 loc) · 6.77 KB
/
yeego.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
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
package main
import (
"encoding/json"
"fmt"
"net/http"
"os"
"runtime"
"runtime/debug"
"runtime/pprof"
"strconv"
"time"
log "github.com/sirupsen/logrus"
"github.com/gorilla/mux"
"github.com/pulento/yeelight"
)
var (
timeSearch = 3
lights = make(map[string]*yeelight.Light)
commandTimeout = 2
ssdpRescan = 3 * time.Minute
)
// APIResult is the response to a command
type APIResult struct {
Result string `json:"result"`
ID string `json:"id,omitempty"`
Params []string `json:"params,omitempty"`
Error *yeelight.Error `json:"error,omitempty"`
}
// Let's roll
func main() {
var err error
//defer profile.Start(profile.MemProfile).Stop()
//defer profile.Start().Stop()
log.SetLevel(log.DebugLevel)
log.Printf("Initial lights search for %d [sec]", timeSearch)
// Start a result/notification listener for each light
resnot := make(chan *yeelight.ResultNotification)
done := make(chan bool)
// Initial search
err = yeelight.Search(timeSearch, "", lights, func(l *yeelight.Light) {
_, lerr := l.Listen(resnot)
if lerr != nil {
log.Errorf("Error connecting to %s: %s", l.Address, err)
}
})
if err != nil {
log.Fatal("Error searching lights cannot continue:", err)
}
log.Infof("Found %d lights", len(lights))
// Start a SSDP monitor for lights traffic
err = yeelight.SSDPMonitor(lights, func(l *yeelight.Light) {
if l.Conn == nil {
// A new light is automatically added but not connected
l.Listen(resnot)
}
})
if err != nil {
log.Errorln("Error starting SSDP monitor", err)
}
go func(c <-chan *yeelight.ResultNotification, done <-chan bool) {
log.Debug("Messages receiver started")
for {
select {
case data := <-c:
// By now just log messages since light data is automatically updated
if data != nil {
if data.Notification != nil {
log.WithFields(log.Fields{
"ID": (*data.Notification).DevID,
"method": (*data.Notification).Method,
}).Debugln("Notification:", (*data.Notification).Params)
} else {
log.WithFields(log.Fields{
"mID": (*data.Result).ID,
"ID": (*data.Result).DevID,
}).Debugln("Result: ", (*data.Result).Result)
}
}
case <-done:
return
}
}
}(resnot, done)
// Every 3 min run a SSDP search again
go func(refresh <-chan time.Time) {
for {
select {
case <-refresh:
log.Info("SSDP rescan")
refresh = time.After(ssdpRescan)
err = yeelight.Search(timeSearch, "", lights, func(l *yeelight.Light) {
_, lerr := l.Listen(resnot)
if lerr != nil {
log.Errorf("Error connecting to %s: %s", l.Address, err)
}
})
if err != nil {
log.Errorln("Error on SSDP rescan: ", err)
}
}
}
}(time.After(ssdpRescan))
var dir = "views"
// Serving HTTP port
port := os.Getenv("YEEGO_PORT")
if port == "" {
port = "8080"
}
router := mux.NewRouter()
router.HandleFunc("/light", GetLights).Methods("GET")
router.HandleFunc("/lights", GetLights).Methods("GET")
router.HandleFunc("/light/{id}", GetLight).Methods("GET")
router.HandleFunc("/light/{id}/toggle", ToggleLight).Methods("GET")
router.HandleFunc("/light/{id}/{command}/{value}", CommandLight).Methods("GET")
// Profile stuff
router.HandleFunc("/_count", GetGoroutinesCount).Methods("GET")
router.HandleFunc("/_stack", GetStackTrace).Methods("GET")
// This will serve files static content
router.PathPrefix("/").Handler(http.StripPrefix("/", http.FileServer(http.Dir(dir))))
log.Info("Listening HTTP: ", port)
log.Fatal(http.ListenAndServe(":"+port, router))
}
// GetGoroutinesCount returns Goroutines count
func GetGoroutinesCount(w http.ResponseWriter, r *http.Request) {
// Get the count of number of go routines running.
count := runtime.NumGoroutine()
json.NewEncoder(w).Encode(count)
//w.Write([]byte(strconv.Itoa(count)))
}
// GetStackTrace dumps stack trace
func GetStackTrace(w http.ResponseWriter, r *http.Request) {
stack := debug.Stack()
w.Write(stack)
pprof.Lookup("goroutine").WriteTo(w, 2)
}
// Index does nothing
func Index(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Yeego")
}
// GetLights returns all lights data
func GetLights(w http.ResponseWriter, r *http.Request) {
var ls []*yeelight.Light
for _, light := range lights {
ls = append(ls, light)
}
json.NewEncoder(w).Encode(ls)
}
// GetLight returns a light data
func GetLight(w http.ResponseWriter, r *http.Request) {
params := mux.Vars(r)
json.NewEncoder(w).Encode(lights[params["id"]])
}
// ToggleLight toggles light power
func ToggleLight(w http.ResponseWriter, r *http.Request) {
var res APIResult
params := mux.Vars(r)
if lights[params["id"]] != nil {
reqid, err := lights[params["id"]].Toggle()
lights[params["id"]].WaitResult(reqid, commandTimeout)
if err != nil {
log.Errorln("Error toggling light:", err)
} else {
res = APIResult{
Result: "ok",
ID: lights[params["id"]].ID,
}
}
} else {
res = APIResult{
Result: "not found",
}
}
json.NewEncoder(w).Encode(res)
}
// CommandLight sends a command with its parameter
func CommandLight(w http.ResponseWriter, r *http.Request) {
var res APIResult
var err error
p := mux.Vars(r)
l := lights[p["id"]]
if l != nil {
var value int
if p["value"] != "" {
value, err = strconv.Atoi(p["value"])
if err != nil {
res = APIResult{
Result: "error",
Params: []string{"invalid value"},
}
}
}
if p["command"] == "brightness" {
if err == nil {
var reqid int32
reqid, err = l.SetBrightness(value, 0)
if err != nil {
res = APIResult{
Result: "error",
Params: []string{err.Error()},
}
log.Errorln("Error setting brightness:", err)
goto end
}
r := l.WaitResult(reqid, commandTimeout)
if r != nil {
if r.Error != nil {
log.Errorln("Error received:", *r.Error)
res = APIResult{
Result: "error",
ID: l.ID,
Error: r.Error,
}
} else {
res = APIResult{
Result: "ok",
ID: l.ID,
}
}
} else {
log.Warnln("Timeout waiting for reply:", reqid)
res = APIResult{
Result: "error",
Params: []string{"timeout setting brightness"},
}
}
} else {
res = APIResult{
Result: "error",
Params: []string{"invalid value"},
}
}
} else if p["command"] == "setname" {
var reqid int32
name := p["value"]
reqid, err = l.SetName(name, 0)
if err != nil {
res = APIResult{
Result: "error",
Params: []string{err.Error()},
}
log.Errorln("Error setting name:", err)
goto end
}
l.WaitResult(reqid, commandTimeout)
} else {
res = APIResult{
Result: "error",
Params: []string{"invalid command"},
}
}
} else {
res = APIResult{
Result: "error",
Params: []string{"not found"},
}
}
end:
json.NewEncoder(w).Encode(res)
}