-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathLedController.go
405 lines (326 loc) · 9.34 KB
/
LedController.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
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
package main
import (
"fmt"
"image"
"image/color"
"io"
"net"
"os"
"time"
"github.com/lucasb-eyer/go-colorful"
"github.com/ninjasphere/go-ninja/api"
"github.com/ninjasphere/go-ninja/config"
"github.com/ninjasphere/go-ninja/logger"
"github.com/ninjasphere/go-ninja/model"
ledmodel "github.com/ninjasphere/sphere-go-led-controller/model"
"github.com/ninjasphere/sphere-go-led-controller/remote"
"github.com/ninjasphere/sphere-go-led-controller/ui"
"github.com/ninjasphere/sphere-go-led-controller/util"
)
var log = logger.GetLogger("sphere-go-led-controller")
var enableRemotePanes = config.Bool(false, "led.remote.enabled")
var remotePort = config.Int(3115, "led.remote.port")
var fps Tick = Tick{
name: "Pane FPS",
}
type LedController struct {
controlEnabled bool
controlRequested bool
controlRendering bool
commandReceived bool
controlLayout *ui.PaneLayout
pairingLayout *ui.PairingLayout
conn *ninja.Connection
serial io.ReadWriteCloser
waiting chan bool
}
func NewLedController(conn *ninja.Connection) (*LedController, error) {
s, err := util.GetLEDConnection()
if err != nil {
log.Fatalf("Failed to get connection to LED matrix: %s", err)
}
// Send a blank image to the led matrix
util.WriteLEDMatrix(image.NewRGBA(image.Rect(0, 0, 16, 16)), s)
controller := &LedController{
conn: conn,
pairingLayout: ui.NewPairingLayout(),
serial: s,
waiting: make(chan bool),
}
conn.MustExportService(controller, "$node/"+config.Serial()+"/led-controller", &model.ServiceAnnouncement{
Schema: "/service/led-controller",
})
conn.MustExportService(controller, "$home/led-controller", &model.ServiceAnnouncement{
Schema: "/service/led-controller",
})
if config.HasString("siteId") {
log.Infof("Have a siteId, checking if homecloud is running")
// If we have just started, and we have a site, and homecloud is running... enable control!
go func() {
siteModel := conn.GetServiceClient("$home/services/SiteModel")
for {
if controller.commandReceived {
log.Infof("Command has been received, stopping search for homecloud.")
break
}
err := siteModel.Call("fetch", config.MustString("siteId"), nil, time.Second*5)
if err != nil {
log.Infof("Fetched site to enableControl. Got err: %s", err)
} else if err == nil && !controller.commandReceived {
controller.EnableControl()
break
}
time.Sleep(time.Second * 5)
}
}()
}
return controller, nil
}
func (c *LedController) start(enableControl bool) {
c.controlRequested = enableControl
frameWritten := make(chan bool)
go func() {
fps.start()
for {
fps.tick()
if c.controlEnabled {
// Good to go
image, wake, err := c.controlLayout.Render()
if err != nil {
log.Fatalf("Unable to render()", err)
}
go func() {
util.WriteLEDMatrix(image, c.serial)
frameWritten <- true
}()
select {
case <-frameWritten:
// All good.
case <-time.After(10 * time.Second):
log.Infof("Timeout writing to LED matrix. Quitting.")
os.Exit(1)
}
if wake != nil {
log.Infof("Waiting as the UI is asleep")
select {
case <-wake:
log.Infof("UI woke up!")
case <-c.waiting:
log.Infof("Got a command from rpc...")
}
}
} else if c.controlRequested && !c.controlRendering {
// We want to display controls, so lets render the pane
c.controlRendering = true
go func() {
log.Infof("Starting control layout")
c.controlLayout = getPaneLayout(c.conn)
c.controlRendering = false
c.controlEnabled = true
log.Infof("Finished control layout")
}()
}
if c.controlRendering || !c.controlEnabled {
// We're either already controlling, or waiting for the pane to render
image, err := c.pairingLayout.Render()
if err != nil {
log.Fatalf("Unable to render()", err)
}
util.WriteLEDMatrix(image, c.serial)
}
}
}()
}
func (c *LedController) EnableControl() error {
log.Infof("Enabling control. Already enabled? %t", c.controlEnabled)
if !c.controlEnabled {
if c.controlLayout != nil {
// Pane layout has already been rendered. Just re-enable control.
c.controlEnabled = true
} else {
c.controlRequested = true
}
c.gotCommand()
}
return nil
}
func (c *LedController) disableControl() error {
log.Infof("Disabling control. Currently enabled? %t", c.controlEnabled)
c.DisplayIcon(&ledmodel.IconRequest{
Icon: "spinner-red.gif",
})
c.controlEnabled = false
c.controlRequested = false
return nil
}
func (c *LedController) DisableControl() error {
c.disableControl()
c.gotCommand()
return nil
}
type PairingCodeRequest struct {
Code string `json:"code"`
DisplayTime int `json:"displayTime"`
}
func (c *LedController) DisplayPairingCode(req *PairingCodeRequest) error {
c.pairingLayout.ShowCode(req.Code)
c.gotCommand()
return nil
}
type ColorRequest struct {
Color string `json:"color"`
DisplayTime int `json:"displayTime"`
}
func (c *LedController) DisplayColor(req *ColorRequest) error {
col, err := colorful.Hex(req.Color)
if err != nil {
return err
}
c.pairingLayout.ShowColor(col)
c.gotCommand()
return nil
}
func (c *LedController) DisplayIcon(req *ledmodel.IconRequest) error {
log.Infof("Displaying icon: %v", req)
c.pairingLayout.ShowIcon(req.Icon)
c.gotCommand()
return nil
}
func (c *LedController) DisplayDrawing() error {
c.pairingLayout.ShowDrawing()
return nil
}
func (c *LedController) Draw(updates *[][]uint8) error {
c.pairingLayout.Draw(updates)
return nil
}
func (c *LedController) DisplayResetMode(m *ledmodel.ResetMode) error {
c.DisableControl()
fade := m.Duration > 0 && !m.Hold
loading := false
var col color.Color
switch m.Mode {
case "abort":
col, _ = colorful.Hex("#FFFFFF")
case "halt":
col, _ = colorful.Hex("#CDC9C9")
case "reboot":
col, _ = colorful.Hex("#00FF00")
case "reset-userdata":
col, _ = colorful.Hex("#FFFF00")
case "reset-root":
col, _ = colorful.Hex("#FF0000")
case "none":
col, _ = colorful.Hex("#FFFFFF")
c.pairingLayout.ShowColor(col)
c.gotCommand()
c.EnableControl()
return nil
default:
loading = true
}
if loading {
c.pairingLayout.ShowIcon("spinner-pink.gif")
} else if fade {
c.pairingLayout.ShowFadingShrinkingColor(col, m.Duration)
} else {
c.pairingLayout.ShowColor(col)
}
c.gotCommand()
return nil
}
func (c *LedController) DisplayUpdateProgress(p *ledmodel.DisplayUpdateProgress) error {
c.disableControl() // copes with situation that homecloud restarts before update is finished
c.pairingLayout.ShowUpdateProgress(p.Progress)
return nil
}
func (c *LedController) gotCommand() {
select {
case c.waiting <- true:
default:
}
c.commandReceived = true
}
// Load from a config file instead...
func getPaneLayout(conn *ninja.Connection) *ui.PaneLayout {
layout, wake := ui.NewPaneLayout(false, conn)
layout.AddPane(ui.NewClockPane())
layout.AddPane(ui.NewWeatherPane(conn))
layout.AddPane(ui.NewGesturePane())
layout.AddPane(ui.NewGameOfLifePane())
layout.AddPane(ui.NewMediaPane(conn))
layout.AddPane(ui.NewCertPane(conn.GetMqttClient()))
//layout.AddPane(ui.NewTextScrollPane("Exit Music (For A Film)"))
lampPane := ui.NewOnOffPane(util.ResolveImagePath("lamp2-off.gif"), util.ResolveImagePath("lamp2-on.gif"), func(state bool) {
log.Debugf("Lamp state: %t", state)
}, conn, "lamp")
layout.AddPane(lampPane)
heaterPane := ui.NewOnOffPane(util.ResolveImagePath("heater-off.png"), util.ResolveImagePath("heater-on.gif"), func(state bool) {
log.Debugf("Heater state: %t", state)
}, conn, "heater")
layout.AddPane(heaterPane)
brightnessPane := ui.NewLightPane(false, util.ResolveImagePath("light-off.png"), util.ResolveImagePath("light-on.png"), conn)
layout.AddPane(brightnessPane)
colorPane := ui.NewLightPane(true, util.ResolveImagePath("light-off.png"), util.ResolveImagePath("light-on.png"), conn)
layout.AddPane(colorPane)
fanPane := ui.NewOnOffPane(util.ResolveImagePath("fan-off.png"), util.ResolveImagePath("fan-on.gif"), func(state bool) {
log.Debugf("Fan state: %t", state)
}, conn, "fan")
layout.AddPane(fanPane)
airconPane := ui.NewOnOffPane(util.ResolveImagePath("fan-off.png"), util.ResolveImagePath("fan-on.gif"), func(state bool) {
log.Debugf("aircon state: %t", state)
}, conn, "aircon")
layout.AddPane(airconPane)
layout.AddPane(ui.NewSystemPane(conn))
if enableRemotePanes {
if err := listenForRemotePanes(layout); err != nil {
log.Fatalf("Failed to start listening for remote panes: %s", err)
}
}
go func() {
<-wake
}()
go layout.Wake()
return layout
}
func listenForRemotePanes(layout *ui.PaneLayout) error {
listener, err := net.Listen("tcp", fmt.Sprintf(":%d", remotePort))
if err != nil {
return err
}
log.Infof("Listening for remote panes on :%d", remotePort)
go func() {
defer listener.Close()
for {
conn, err := listener.Accept()
if err != nil {
log.Fatalf("Error accepting remote pane: %s", err)
}
go func() {
log.Infof("Remote pane connected.")
pane := remote.NewPane(conn)
layout.AddPane(pane)
<-pane.Disconnected
log.Infof("Remote pane disconnected.")
layout.RemovePane(pane)
}()
}
}()
return nil
}
type Tick struct {
count int
name string
}
func (t *Tick) tick() {
t.count++
}
func (t *Tick) start() {
go func() {
for {
time.Sleep(time.Second)
//log.Debugf("%s - %d", t.name, t.count)
t.count = 0
}
}()
}