-
Notifications
You must be signed in to change notification settings - Fork 4
/
devicequery.go
72 lines (61 loc) · 1.33 KB
/
devicequery.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
package windevice
import (
"io"
"github.com/gentlemanautomaton/windevice/setupapi"
"golang.org/x/sys/windows"
)
// DeviceQuery holds device query information. Its zero value is a valid query
// for all devices.
type DeviceQuery struct {
Class windows.GUID
Enumerator string
Flags uint32
Machine string // TODO: Consider removing this if it's not well supported
Selector DeviceSelector
}
// Count returns the number of devices matching the query.
func (q DeviceQuery) Count() (int, error) {
var total int
err := q.Each(func(Device) {
total++
})
return total, err
}
// Each performs an action on each device that matches the query.
func (q DeviceQuery) Each(action DeviceActor) error {
var classPtr *windows.GUID
if q.Class != zeroGUID {
classPtr = &q.Class
}
devices, err := setupapi.GetClassDevsEx(classPtr, q.Enumerator, q.Flags, 0, q.Machine)
if err != nil {
return err
}
defer setupapi.DestroyDeviceInfoList(devices)
i := uint32(0)
for {
device, err := setupapi.EnumDeviceInfo(devices, i)
switch err {
case nil:
case io.EOF:
return nil
default:
return err
}
i++
d := Device{
devices: devices,
data: device,
}
if q.Selector != nil {
matched, err := q.Selector.Select(d)
if err != nil {
return err
}
if !matched {
continue
}
}
action(d)
}
}