2014-03-23 09:39:31 +01:00
|
|
|
// Generic LED driver.
|
|
|
|
|
2014-03-23 01:55:32 +01:00
|
|
|
package embd
|
|
|
|
|
|
|
|
import (
|
|
|
|
"errors"
|
|
|
|
"fmt"
|
|
|
|
"strconv"
|
|
|
|
)
|
|
|
|
|
2014-03-23 09:39:31 +01:00
|
|
|
// LEDMap type represents a LED mapping for a host.
|
2014-03-23 01:55:32 +01:00
|
|
|
type LEDMap map[string][]string
|
|
|
|
|
2014-04-06 03:20:09 +02:00
|
|
|
type ledFactory func(string) LED
|
|
|
|
|
2014-03-23 01:55:32 +01:00
|
|
|
type ledDriver struct {
|
|
|
|
ledMap LEDMap
|
|
|
|
|
2014-04-06 03:20:09 +02:00
|
|
|
lf ledFactory
|
|
|
|
|
2014-03-23 01:55:32 +01:00
|
|
|
initializedLEDs map[string]LED
|
|
|
|
}
|
|
|
|
|
2014-04-06 03:20:09 +02:00
|
|
|
// NewLEDDriver returns a LEDDriver interface which allows control
|
|
|
|
// over the LED subsystem.
|
|
|
|
func NewLEDDriver(ledMap LEDMap, lf ledFactory) LEDDriver {
|
2014-03-23 01:55:32 +01:00
|
|
|
return &ledDriver{
|
2014-04-06 03:20:09 +02:00
|
|
|
ledMap: ledMap,
|
|
|
|
lf: lf,
|
|
|
|
|
2014-03-23 01:55:32 +01:00
|
|
|
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
|
|
|
|
}
|
|
|
|
|
2014-04-06 03:20:09 +02:00
|
|
|
led := d.lf(id)
|
2014-03-23 01:55:32 +01:00
|
|
|
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
|
|
|
|
}
|