-
Notifications
You must be signed in to change notification settings - Fork 110
/
board.go
403 lines (341 loc) · 10.3 KB
/
board.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
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
// Package fake implements a fake board.
package fake
import (
"context"
"fmt"
"sync"
"github.com/edaniels/golog"
"github.com/pkg/errors"
"go.uber.org/multierr"
commonpb "go.viam.com/api/common/v1"
"go.viam.com/utils"
"go.viam.com/rdk/components/board"
"go.viam.com/rdk/components/generic"
"go.viam.com/rdk/config"
"go.viam.com/rdk/registry"
"go.viam.com/rdk/resource"
)
var _ = board.LocalBoard(&Board{})
// A Config describes the configuration of an arduino board and all of its connected parts.
type Config struct {
I2Cs []board.I2CConfig `json:"i2cs,omitempty"`
SPIs []board.SPIConfig `json:"spis,omitempty"`
Analogs []board.AnalogConfig `json:"analogs,omitempty"`
DigitalInterrupts []board.DigitalInterruptConfig `json:"digital_interrupts,omitempty"`
Attributes config.AttributeMap `json:"attributes,omitempty"`
FailNew bool `json:"fail_new"`
}
// Validate ensures all parts of the config are valid.
func (config *Config) Validate(path string) error {
for idx, conf := range config.SPIs {
if err := conf.Validate(fmt.Sprintf("%s.%s.%d", path, "spis", idx)); err != nil {
return err
}
}
for idx, conf := range config.I2Cs {
if err := conf.Validate(fmt.Sprintf("%s.%s.%d", path, "i2cs", idx)); err != nil {
return err
}
}
for idx, conf := range config.Analogs {
if err := conf.Validate(fmt.Sprintf("%s.%s.%d", path, "analogs", idx)); err != nil {
return err
}
}
for idx, conf := range config.DigitalInterrupts {
if err := conf.Validate(fmt.Sprintf("%s.%s.%d", path, "digital_interrupts", idx)); err != nil {
return err
}
}
if config.FailNew {
return errors.New("whoops")
}
return nil
}
var modelName = resource.NewDefaultModel("fake")
func init() {
registry.RegisterComponent(
board.Subtype,
modelName,
registry.Component{Constructor: func(
ctx context.Context,
_ registry.Dependencies,
cfg config.Component,
logger golog.Logger,
) (interface{}, error) {
return NewBoard(ctx, cfg, logger)
}})
config.RegisterComponentAttributeMapConverter(
board.Subtype,
modelName,
func(attributes config.AttributeMap) (interface{}, error) {
var conf Config
return config.TransformAttributeMapToStruct(&conf, attributes)
},
&Config{})
}
// NewBoard returns a new fake board.
func NewBoard(ctx context.Context, config config.Component, logger golog.Logger) (*Board, error) {
boardConfig, ok := config.ConvertedAttributes.(*Config)
if !ok {
return nil, errors.Errorf("expected converted attributes to be a *board.Config but got %T", config.ConvertedAttributes)
}
b := &Board{
Name: config.Name,
I2Cs: map[string]*I2C{},
SPIs: map[string]*SPI{},
Analogs: map[string]*Analog{},
Digitals: map[string]board.DigitalInterrupt{},
GPIOPins: map[string]*GPIOPin{},
}
for _, c := range boardConfig.I2Cs {
b.I2Cs[c.Name] = &I2C{}
}
for _, c := range boardConfig.SPIs {
b.SPIs[c.Name] = &SPI{}
}
for _, c := range boardConfig.Analogs {
b.Analogs[c.Name] = &Analog{}
}
for _, c := range boardConfig.DigitalInterrupts {
var err error
b.Digitals[c.Name], err = board.CreateDigitalInterrupt(c)
if err != nil {
return nil, err
}
}
return b, nil
}
// UpdateAction helps hinting the reconfiguration process on what strategy to use given a modified config.
// See config.UpdateActionType for more information.
func (b *Board) UpdateAction(c *config.Component) config.UpdateActionType {
_, ok := c.ConvertedAttributes.(*Config)
if !ok {
return config.Rebuild
}
return config.Reconfigure
}
// A Board provides dummy data from fake parts in order to implement a Board.
type Board struct {
generic.Echo
Name string
SPIs map[string]*SPI
I2Cs map[string]*I2C
Analogs map[string]*Analog
Digitals map[string]board.DigitalInterrupt
GPIOPins map[string]*GPIOPin
CloseCount int
}
// SPIByName returns the SPI by the given name if it exists.
func (b *Board) SPIByName(name string) (board.SPI, bool) {
s, ok := b.SPIs[name]
return s, ok
}
// I2CByName returns the i2c by the given name if it exists.
func (b *Board) I2CByName(name string) (board.I2C, bool) {
s, ok := b.I2Cs[name]
return s, ok
}
// AnalogReaderByName returns the analog reader by the given name if it exists.
func (b *Board) AnalogReaderByName(name string) (board.AnalogReader, bool) {
a, ok := b.Analogs[name]
return a, ok
}
// DigitalInterruptByName returns the interrupt by the given name if it exists.
func (b *Board) DigitalInterruptByName(name string) (board.DigitalInterrupt, bool) {
d, ok := b.Digitals[name]
return d, ok
}
// GPIOPinByName returns the GPIO pin by the given name if it exists.
func (b *Board) GPIOPinByName(name string) (board.GPIOPin, error) {
p, ok := b.GPIOPins[name]
if !ok {
pin := &GPIOPin{}
b.GPIOPins[name] = pin
return pin, nil
}
return p, nil
}
// SPINames returns the name of all known SPIs.
func (b *Board) SPINames() []string {
names := []string{}
for k := range b.SPIs {
names = append(names, k)
}
return names
}
// I2CNames returns the name of all known I2Cs.
func (b *Board) I2CNames() []string {
names := []string{}
for k := range b.I2Cs {
names = append(names, k)
}
return names
}
// AnalogReaderNames returns the name of all known analog readers.
func (b *Board) AnalogReaderNames() []string {
names := []string{}
for k := range b.Analogs {
names = append(names, k)
}
return names
}
// DigitalInterruptNames returns the name of all known digital interrupts.
func (b *Board) DigitalInterruptNames() []string {
names := []string{}
for k := range b.Digitals {
names = append(names, k)
}
return names
}
// GPIOPinNames returns the name of all known digital interrupts.
func (b *Board) GPIOPinNames() []string {
names := []string{}
for k := range b.GPIOPins {
names = append(names, k)
}
return names
}
// Status returns the current status of the board.
func (b *Board) Status(ctx context.Context, extra map[string]interface{}) (*commonpb.BoardStatus, error) {
return board.CreateStatus(ctx, b, extra)
}
// ModelAttributes returns attributes related to the model of this board.
func (b *Board) ModelAttributes() board.ModelAttributes {
return board.ModelAttributes{}
}
// Close attempts to cleanly close each part of the board.
func (b *Board) Close(ctx context.Context) error {
b.CloseCount++
var err error
for _, analog := range b.Analogs {
err = multierr.Combine(err, utils.TryClose(ctx, analog))
}
for _, digital := range b.Digitals {
err = multierr.Combine(err, utils.TryClose(ctx, digital))
}
return err
}
// A SPI allows opening an SPIHandle.
type SPI struct {
mu sync.Mutex
FIFO chan []byte
}
// OpenHandle opens a handle to perform SPI transfers that must be later closed to release access to the bus.
func (s *SPI) OpenHandle() (board.SPIHandle, error) {
s.mu.Lock()
return &SPIHandle{s}, nil
}
// A SPIHandle allows Xfer and Close.
type SPIHandle struct {
bus *SPI
}
// Xfer transfers the given data.
func (h *SPIHandle) Xfer(ctx context.Context, baud uint, chipSelect string, mode uint, tx []byte) ([]byte, error) {
h.bus.FIFO <- tx
ret := <-h.bus.FIFO
return ret[:len(tx)], nil
}
// Close releases access to the bus.
func (h *SPIHandle) Close() error {
h.bus.mu.Unlock()
return nil
}
// A I2C allows opening an I2CHandle.
type I2C struct {
mu sync.Mutex
fifo chan []byte
}
// OpenHandle opens a handle to perform I2C transfers that must be later closed to release access to the bus.
func (s *I2C) OpenHandle(addr byte) (board.I2CHandle, error) {
s.mu.Lock()
return &I2CHandle{s, addr}, nil
}
// A I2CHandle allows read/write and Close.
type I2CHandle struct {
bus *I2C
addr byte
}
func (h *I2CHandle) Write(ctx context.Context, tx []byte) error {
h.bus.fifo <- tx
return nil
}
func (h *I2CHandle) Read(ctx context.Context, count int) ([]byte, error) {
ret := <-h.bus.fifo
return ret[:count], nil
}
// ReadByteData reads a byte from the i2c channel.
func (h *I2CHandle) ReadByteData(ctx context.Context, register byte) (byte, error) {
return 0, errors.New("finish me")
}
// WriteByteData writes a byte to the i2c channel.
func (h *I2CHandle) WriteByteData(ctx context.Context, register, data byte) error {
return errors.New("finish me")
}
// ReadBlockData reads the given number of bytes from the i2c channel.
func (h *I2CHandle) ReadBlockData(ctx context.Context, register byte, numBytes uint8) ([]byte, error) {
return nil, errors.New("finish me")
}
// WriteBlockData writes the given bytes to the i2c channel.
func (h *I2CHandle) WriteBlockData(ctx context.Context, register byte, data []byte) error {
return errors.New("finish me")
}
// Close releases access to the bus.
func (h *I2CHandle) Close() error {
h.bus.mu.Unlock()
return nil
}
// A Analog reads back the same set value.
type Analog struct {
Value int
CloseCount int
Mu sync.RWMutex
}
func (a *Analog) Read(ctx context.Context, extra map[string]interface{}) (int, error) {
a.Mu.RLock()
defer a.Mu.RUnlock()
return a.Value, nil
}
// Set is used during testing.
func (a *Analog) Set(value int) {
a.Mu.Lock()
defer a.Mu.Unlock()
a.Value = value
}
// Close does nothing.
func (a *Analog) Close() {
a.CloseCount++
}
// A GPIOPin reads back the same set values.
type GPIOPin struct {
high bool
pwm float64
pwmFreq uint
}
// Set sets the pin to either low or high.
func (gp *GPIOPin) Set(ctx context.Context, high bool, extra map[string]interface{}) error {
gp.high = high
return nil
}
// Get gets the high/low state of the pin.
func (gp *GPIOPin) Get(ctx context.Context, extra map[string]interface{}) (bool, error) {
return gp.high, nil
}
// PWM gets the pin's given duty cycle.
func (gp *GPIOPin) PWM(ctx context.Context, extra map[string]interface{}) (float64, error) {
return gp.pwm, nil
}
// SetPWM sets the pin to the given duty cycle.
func (gp *GPIOPin) SetPWM(ctx context.Context, dutyCyclePct float64, extra map[string]interface{}) error {
gp.pwm = dutyCyclePct
return nil
}
// PWMFreq gets the PWM frequency of the pin.
func (gp *GPIOPin) PWMFreq(ctx context.Context, extra map[string]interface{}) (uint, error) {
return gp.pwmFreq, nil
}
// SetPWMFreq sets the given pin to the given PWM frequency. 0 will use the board's default PWM frequency.
func (gp *GPIOPin) SetPWMFreq(ctx context.Context, freqHz uint, extra map[string]interface{}) error {
gp.pwmFreq = freqHz
return nil
}