forked from kidoman/embd
-
Notifications
You must be signed in to change notification settings - Fork 3
/
leddriver.go
79 lines (62 loc) · 1.29 KB
/
leddriver.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
// Generic LED driver.
package embd
import (
"errors"
"fmt"
"strconv"
)
// LEDMap type represents a LED mapping for a host.
type LEDMap map[string][]string
type ledFactory func(string) LED
type ledDriver struct {
ledMap LEDMap
lf ledFactory
initializedLEDs map[string]LED
}
// NewLEDDriver returns a LEDDriver interface which allows control
// over the LED subsystem.
func NewLEDDriver(ledMap LEDMap, lf ledFactory) LEDDriver {
return &ledDriver{
ledMap: ledMap,
lf: lf,
initializedLEDs: map[string]LED{},
}
}
func (d *ledDriver) lookup(k interface{}) (string, error) {
var ks string
switch key := k.(type) {
case int:
ks = strconv.Itoa(key)
case string:
ks = key
case fmt.Stringer:
ks = key.String()
default:
return "", errors.New("led: invalid key type")
}
for id := range d.ledMap {
for _, alias := range d.ledMap[id] {
if alias == ks {
return id, nil
}
}
}
return "", fmt.Errorf("led: no match found for %q", k)
}
func (d *ledDriver) LED(k interface{}) (LED, error) {
id, err := d.lookup(k)
if err != nil {
return nil, err
}
led := d.lf(id)
d.initializedLEDs[id] = led
return led, nil
}
func (d *ledDriver) Close() error {
for _, led := range d.initializedLEDs {
if err := led.Close(); err != nil {
return err
}
}
return nil
}