-
Notifications
You must be signed in to change notification settings - Fork 0
/
controller_func.go
390 lines (337 loc) · 11.3 KB
/
controller_func.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
package blink1
import (
"errors"
"fmt"
"image/color"
"time"
)
var (
errInvalidPosition = errors.New("b1: invalid pattern position")
errInvalidRepeatTimes = errors.New("b1: invalid pattern repeat times")
errInvalidTimeout = errors.New("b1: invalid timeout")
)
// GetFirmwareVersion returns the firmware version of the device.
func (c *Controller) GetFirmwareVersion() (int, error) {
return c.dev.GetVersion()
}
// PlayStateBlocking fades the given LED to the specified RGB color over the specified time, and blocks until the fade is finished.
func (c *Controller) PlayStateBlocking(st LightState) error {
// NOTE: no lock here, since PlayState will lock
// play state
if err := c.PlayState(st); err != nil {
return err
}
// block until fade is finished
if dur := convDurationToActual(st.FadeTime); dur > 0 {
time.Sleep(dur)
}
return nil
}
// PlayState fades the given LED to the specified RGB color over the specified time.
func (c *Controller) PlayState(st LightState) error {
c.mu.Lock()
defer c.mu.Unlock()
r, g, b := convColorToRGB(st.Color)
if c.gamma {
r, g, b = degammaRGB(r, g, b)
}
msec := uint(st.FadeTime.Milliseconds())
return c.dev.FadeToRGB(r, g, b, msec, st.LED)
}
// PlayColor fades the all LED to the specified RGB color immediately.
func (c *Controller) PlayColor(cl color.Color) error {
c.mu.Lock()
defer c.mu.Unlock()
r, g, b := convColorToRGB(cl)
if c.gamma {
r, g, b = degammaRGB(r, g, b)
}
return c.dev.SetRGBNow(r, g, b, LEDAll)
}
// PlayRGB fades the all LED to the specified RGB color immediately.
func (c *Controller) PlayRGB(r, g, b byte) error {
c.mu.Lock()
defer c.mu.Unlock()
return c.dev.SetRGBNow(r, g, b, LEDAll)
}
// PlayHSB fades the all LED to the specified HSB/HSV color immediately.
// Valid hue range is [0, 360], saturation range and brightness/value range is [0, 100].
// Values outside of the valid range will be clamped to the range.
func (c *Controller) PlayHSB(hue, saturation, brightness float64) error {
c.mu.Lock()
defer c.mu.Unlock()
r, g, b := convHSBToRGB(hue, saturation, brightness)
if c.gamma {
r, g, b = degammaRGB(r, g, b)
}
return c.dev.SetRGBNow(r, g, b, LEDAll)
}
// ReadColor reads the current color of the specified LED.
func (c *Controller) ReadColor(ledN LEDIndex) (color.Color, error) {
c.mu.Lock()
defer c.mu.Unlock()
r, g, b, err := c.dev.ReadRGB(ledN)
if err != nil {
return nil, fmt.Errorf("b1: failed to read rgb: %w", err)
}
return convRGBToColor(r, g, b), nil
}
// PlayPatternBlocking plays the given pattern, and blocks until the pattern is finished. It may block forever if the pattern is set to loop forever.
// If the pattern has no states, it will only play the pattern without writing states to the device's RAM, and blocks until the pattern is finished.
func (c *Controller) PlayPatternBlocking(pt Pattern) error {
// NOTE: no lock here, since PlayPattern will lock
// play pattern
if err := c.PlayPattern(pt); err != nil {
return err
}
// block until pattern is finished
if pt.RepeatTimes == 0 {
// infinite loop, block forever
<-make(chan struct{})
} else {
// otherwise read pattern to get total duration
startPos, endPos := pt.StartPosition, pt.EndPosition
if endPos == 0 {
endPos = getMaxPattern(c.dev.gen) - 1
}
// read pattern to get total duration
var totalDur time.Duration
for i := startPos; i <= endPos; i++ {
var st DeviceLightState
if err := retryWorkload(func() (ie error) {
st, ie = c.dev.ReadPatternLine(i)
return ie
}); err == nil {
totalDur += time.Duration(st.FadeTimeMsec) * time.Millisecond
} else {
return fmt.Errorf("b1: failed to read pattern line %d: %w", i, err)
}
}
// sleep for total duration
time.Sleep(totalDur * time.Duration(pt.RepeatTimes))
}
return nil
}
// PlayPattern plays the given pattern. If the pattern has no states, it will only play the pattern without writing states to the device's RAM
func (c *Controller) PlayPattern(pt Pattern) error {
c.mu.Lock()
defer c.mu.Unlock()
// ensure range is valid
if !c.isPosRangeValid(pt.StartPosition, pt.EndPosition) {
return errInvalidPosition
}
if pt.RepeatTimes > maxRepeat {
return errInvalidRepeatTimes
}
if pt.EndPosition == 0 {
pt.EndPosition = getMaxPattern(c.dev.gen) - 1
}
// load pattern to RAM
if err := c.loadStateSequence(pt.StartPosition, pt.EndPosition, pt.Sequence); err != nil {
return err
}
// play pattern
return c.dev.PlayLoop(true, pt.StartPosition, pt.EndPosition, pt.RepeatTimes)
}
// LoadPattern writes the given pattern to the device's RAM and it will be lost after the device is powered off.
// To save the pattern to the device's flash, call WritePattern() after calling this function.
func (c *Controller) LoadPattern(posStart, posEnd uint, seq StateSequence) error {
c.mu.Lock()
defer c.mu.Unlock()
// load pattern to RAM
return c.loadStateSequence(posStart, posEnd, seq)
}
// loadStateSequence loads the given pattern to the device's RAM.
func (c *Controller) loadStateSequence(posStart, posEnd uint, seq StateSequence) error {
sc := len(seq) // sc for state counter
if sc == 0 {
// no states, just do nothing
return nil
}
if !c.isPosRangeValid(posStart, posEnd) {
// ensure range is valid
return errInvalidPosition
}
if posEnd == 0 {
// set posEnd to patt_max-1 if posEnd == 0
posEnd = getMaxPattern(c.dev.gen) - 1
}
// set patterns
pc := 0 // pc for position counter
for pos := posStart; pos <= posEnd; pos++ {
// convert state with degamma and set as pattern
st := convLightState(seq[pc])
if c.gamma {
st.R, st.G, st.B = degammaRGB(st.R, st.G, st.B)
}
// operate on device
if err := retryWorkload(func() error {
return c.dev.SetPatternLine(pos, st)
}); err != nil {
return fmt.Errorf("b1: failed to set pattern line %d: %w", pos, err)
}
// quit if all left states are filled
if pc++; pc >= sc {
break
}
// sleep for a little while to avoid hardware errors
time.Sleep(opsInterval)
}
return nil
}
// ReadPattern reads the current pattern in the device's RAM.
func (c *Controller) ReadPattern() (StateSequence, error) {
c.mu.Lock()
defer c.mu.Unlock()
var ls StateSequence
for pos, posMax := uint(0), getMaxPattern(c.dev.gen); pos < posMax; pos++ {
var st DeviceLightState
if err := retryWorkload(func() (ie error) {
st, ie = c.dev.ReadPatternLine(pos)
return ie
}); err != nil {
return nil, fmt.Errorf("b1: failed to read pattern line %d: %w", pos, err)
}
ls = append(ls, convDeviceLightState(st))
}
return ls, nil
}
// WritePattern writes the pattern stored in the device's RAM to its flash. For mk2 device, only the first 16 patterns can be saved.
func (c *Controller) WritePattern() error {
c.mu.Lock()
defer c.mu.Unlock()
return c.dev.SavePattern()
}
// IsPatternPlaying returns true if the pattern is playing.
func (c *Controller) IsPatternPlaying() (bool, error) {
c.mu.Lock()
defer c.mu.Unlock()
st, err := c.dev.ReadPlaystate()
if err != nil {
return false, fmt.Errorf("b1: failed to read play state: %w", err)
}
return st.IsPlaying, nil
}
// GetPatternState returns the current state of the pattern that is playing.
func (c *Controller) GetPatternState() (PatternState, error) {
c.mu.Lock()
defer c.mu.Unlock()
st, err := c.dev.ReadPlaystate()
if err != nil {
return PatternState{}, err
}
return PatternState{
IsPlaying: st.IsPlaying,
CurrentPosition: st.CurrentPos,
StartPosition: st.LoopStartPos,
EndPosition: st.LoopEndPos,
RepeatTimes: st.RepeatTimes,
}, nil
}
// StopPlaying stops playing the pattern and turns off all the LEDs.
// It will stop the current playing patterns, whether it is started by StartPlaying() or StartAuto/ManualTickle(), and turn off all the LEDs.
// If the pattern is not playing, it only turns off all the LEDs.
// It will NOT stop the auto/manual tickle.
func (c *Controller) StopPlaying() error {
c.mu.Lock()
defer c.mu.Unlock()
return c.dev.SetTickleMode(false, false, 0, 0, 0)
}
// StartAutoTickle sets the device to automatically tickle every 2 seconds.
// If the auto tickle is already started, it will be stopped and restarted.
// If keepOld is true, the current pattern will be kept playing, otherwise it will be stopped.
//
// To stop the auto tickle, call StopAutoTickle().
func (c *Controller) StartAutoTickle(posStart, posEnd uint, keepOld bool) error {
c.mu.Lock()
defer c.mu.Unlock()
// ensure range is valid
if !c.isPosRangeValid(posStart, posEnd) {
return errInvalidPosition
}
// if already started, stop it first
if c.quitCh != nil {
close(c.quitCh)
}
// prepare timeout ticker
timeout := 2 * time.Second
timeoutMsec := uint(timeout.Milliseconds())
timeoutMsec += timeoutMsec >> 1 // add 50% to timeout
ticker := time.NewTicker(timeout)
c.quitCh = make(chan struct{})
// start auto tickle
go func() {
for {
select {
case <-ticker.C:
_ = c.dev.SetTickleMode(true, keepOld, posStart, posEnd, timeoutMsec)
case <-c.quitCh:
// quit when tickQuit is closed
ticker.Stop()
_ = c.dev.SetTickleMode(false, keepOld, 0, 0, 0)
return
}
}
}()
return nil
}
// StopAutoTickle stops the device from automatically tickling.
func (c *Controller) StopAutoTickle() {
c.mu.Lock()
defer c.mu.Unlock()
if c.quitCh != nil {
close(c.quitCh)
}
}
// SimpleTickle sets the device to tickle once.
// The timeout should be at least 10ms, or it will be ignored by the firmware. An error will be returned for this case.
// If keepOld is true, the current pattern will be kept playing, otherwise it will be stopped.
func (c *Controller) SimpleTickle(posStart, posEnd uint, timeout time.Duration, keepOld bool) error {
c.mu.Lock()
defer c.mu.Unlock()
// ensure start < end and end < max
if !c.isPosRangeValid(posStart, posEnd) {
return errInvalidPosition
}
if timeout < minTimeDur {
return errInvalidTimeout
}
timeoutMsec := uint(timeout.Milliseconds())
// tickle once
return c.dev.SetTickleMode(true, keepOld, posStart, posEnd, timeoutMsec)
}
// StartManualTickle sets the device to tickle manually.
// The timeout should be at least 10ms, or it will be ignored by the firmware. An error will be returned for this case.
// Signals should be sent to the returned channel to tickle before the timeout, otherwise the given pattern will be played.
// If keepOld is true, the current pattern will be kept playing, otherwise it will be stopped.
//
// To stop the manual tickle, close the returned channel.
func (c *Controller) StartManualTickle(posStart, posEnd uint, timeout time.Duration, keepOld bool) (chan<- struct{}, error) {
c.mu.Lock()
defer c.mu.Unlock()
// ensure start < end and end < max
if !c.isPosRangeValid(posStart, posEnd) {
return nil, errInvalidPosition
}
if timeout < minTimeDur {
return nil, errInvalidTimeout
}
// prepare manual ticker
tickCh := make(chan struct{})
timeoutMsec := uint(timeout.Milliseconds())
// start tickle
go func() {
for range tickCh {
_ = c.dev.SetTickleMode(true, keepOld, posStart, posEnd, timeoutMsec)
}
// quit when tickCh is closed
_ = c.dev.SetTickleMode(false, keepOld, 0, 0, 0)
}()
return tickCh, nil
}
// isPosRangeValid checks if the given position range is valid.
func (c *Controller) isPosRangeValid(start, end uint) bool {
// check pattern to ensure start <= end and end < max, 0 is a special case equals to last position
mp := getMaxPattern(c.dev.gen)
return (start <= end && end < mp) || (start < mp && end == 0)
}