-
Notifications
You must be signed in to change notification settings - Fork 13
/
led.go
96 lines (82 loc) · 2.34 KB
/
led.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
package led
import (
"errors"
"fmt"
"github.com/boombuler/hid"
"image/color"
)
// Device type identifies the device type. the IDs may change on each program start.
type DeviceType int
// String returns a representation of the device type
func (dt DeviceType) String() string {
idx := int(dt)
if idx < 0 || idx >= len(drivers) {
return ""
}
return drivers[idx].name()
}
type driver interface {
name() string
convert(hDev *hid.DeviceInfo) DeviceInfo
}
var drivers = []driver{}
func addDriver(drv driver) DeviceType {
dt := DeviceType(len(drivers))
drivers = append(drivers, drv)
return dt
}
// Some devices does not support KeepActive.
var ErrKeepActiveNotSupported = errors.New("KeepActive is not supported by this device")
// Device is an opened LED device.
type Device interface {
// SetColor sets the color of the LED to the closest supported color.
SetColor(c color.Color) error
// SetKeepActive sets a value that tells the device not turn off the device on calling Close. By default the device is turned off!
SetKeepActive(v bool) error
// Close the device and release all resources
Close()
}
// DeviceInfo keeps information about a physical LED device
type DeviceInfo interface {
// GetPath returns a system specific path which can be used to find the device
GetPath() string
// GetType returns the "driver type" of the device
GetType() DeviceType
// Open opens the device for usage
Open() (Device, error)
}
// Devices returns a channel with all connected LED devices
func Devices() <-chan DeviceInfo {
result := make(chan DeviceInfo)
go func() {
for d := range hid.Devices() {
di := toLedDeviceInfo(d)
if di != nil {
result <- di
}
}
close(result)
}()
return result
}
// ByPath searches a device by given system specific path. (The path can be obtained from the GetPath func from DeviceInfo)
func ByPath(path string) (DeviceInfo, error) {
hd, err := hid.ByPath(path)
if err != nil {
return nil, err
}
led := toLedDeviceInfo(hd)
if led == nil {
return nil, fmt.Errorf("Unknown LED device (VID: %v, PID: %v)", hd.VendorId, hd.ProductId)
}
return led, nil
}
func toLedDeviceInfo(dev *hid.DeviceInfo) DeviceInfo {
for _, drv := range drivers {
di := drv.convert(dev)
if di != nil {
return di
}
}
return nil
}