-
Notifications
You must be signed in to change notification settings - Fork 0
/
usbrelay.go
86 lines (70 loc) · 1.42 KB
/
usbrelay.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
package usbrelay
import (
"fmt"
"github.com/karalabe/hid"
"strconv"
"strings"
)
func Enumerate() ([]*Device, error) {
deviceInfos := hid.Enumerate(DeviceVendorID, DeviceProductID)
devices := make([]*Device, 0)
if len(deviceInfos) <= 0 {
return devices, ErrNoDeviceFound
}
var (
err error
numRelays int
)
for _, info := range deviceInfos {
if !strings.HasPrefix(info.Product, relayNamePrefix) {
continue
}
numRelaysStr, found := strings.CutPrefix(info.Product, relayNamePrefix)
if !found {
continue
}
numRelays, err = strconv.Atoi(numRelaysStr)
if err != nil {
return devices, err
}
if numRelays < 0 && numRelays != R_ALL {
return nil, fmt.Errorf("%w num relays: %d", ErrInvalidNumberOfRelays, numRelays)
}
var device *Device
device, err = newDevice(&info, numRelays)
if err != nil {
break
}
err = device.Open(false)
if err != nil {
break
}
_, err = device.GetSerialNumber()
if err != nil {
break
}
devices = append(devices, device)
}
for _, device := range devices {
device.Close()
}
if err != nil {
return nil, err
}
if len(devices) <= 0 {
return devices, ErrNoDeviceFound
}
return devices, err
}
func GetDeviceBySerialNumber(sn SerialNumber) (*Device, error) {
devices, err := Enumerate()
if err != nil {
return nil, err
}
for _, d := range devices {
if d.serialNumber == sn {
return d, nil
}
}
return nil, ErrNoDeviceFound
}