-
Notifications
You must be signed in to change notification settings - Fork 110
/
collector.go
101 lines (85 loc) · 2.26 KB
/
collector.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
97
98
99
100
101
package board
import (
"context"
"google.golang.org/protobuf/types/known/anypb"
"go.viam.com/rdk/data"
)
type method int64
const (
analogs method = iota
gpios
)
func (m method) String() string {
if m == analogs {
return "Analogs"
}
if m == gpios {
return "Gpios"
}
return "Unknown"
}
// AnalogRecords a collection of AnalogRecord.
type AnalogRecords struct {
Readings []AnalogRecord
}
// AnalogRecord a single analog reading.
type AnalogRecord struct {
AnalogName string
AnalogValue int
}
// GpioRecords a collection of GpioRecord.
type GpioRecords struct {
Readings []GpioRecord
}
// GpioRecord a signle gpio reading.
type GpioRecord struct {
GPIOName string
GPIOValue bool
}
func newAnalogCollector(resource interface{}, params data.CollectorParams) (data.Collector, error) {
board, err := assertBoard(resource)
if err != nil {
return nil, err
}
cFunc := data.CaptureFunc(func(ctx context.Context, arg map[string]*anypb.Any) (interface{}, error) {
var readings []AnalogRecord
for k := range arg {
if reader, ok := board.AnalogReaderByName(k); ok {
value, err := reader.Read(ctx, nil)
if err != nil {
return nil, data.FailedToReadErr(params.ComponentName, analogs.String(), err)
}
readings = append(readings, AnalogRecord{AnalogName: k, AnalogValue: value})
}
}
return AnalogRecords{Readings: readings}, nil
})
return data.NewCollector(cFunc, params)
}
func newGPIOCollector(resource interface{}, params data.CollectorParams) (data.Collector, error) {
board, err := assertBoard(resource)
if err != nil {
return nil, err
}
cFunc := data.CaptureFunc(func(ctx context.Context, arg map[string]*anypb.Any) (interface{}, error) {
var readings []GpioRecord
for k := range arg {
if gpio, err := board.GPIOPinByName(k); err == nil {
value, err := gpio.Get(ctx, nil)
if err != nil {
return nil, data.FailedToReadErr(params.ComponentName, gpios.String(), err)
}
readings = append(readings, GpioRecord{GPIOName: k, GPIOValue: value})
}
}
return GpioRecords{Readings: readings}, nil
})
return data.NewCollector(cFunc, params)
}
func assertBoard(resource interface{}) (Board, error) {
board, ok := resource.(Board)
if !ok {
return nil, data.InvalidInterfaceErr(SubtypeName)
}
return board, nil
}