-
Notifications
You must be signed in to change notification settings - Fork 110
/
board.go
667 lines (573 loc) · 18.2 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
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
// Package board defines the interfaces that typically live on a single-board computer
// such as a Raspberry Pi.
//
// Besides the board itself, some other interfaces it defines are analog readers and digital interrupts.
package board
import (
"context"
"sync"
"github.com/edaniels/golog"
commonpb "go.viam.com/api/common/v1"
pb "go.viam.com/api/component/board/v1"
viamutils "go.viam.com/utils"
"go.viam.com/utils/rpc"
"go.viam.com/rdk/components/generic"
"go.viam.com/rdk/config"
"go.viam.com/rdk/registry"
"go.viam.com/rdk/resource"
"go.viam.com/rdk/robot"
"go.viam.com/rdk/subtype"
"go.viam.com/rdk/utils"
)
// NewUnimplementedInterfaceError is used when there is a failed interface check.
func NewUnimplementedInterfaceError(actual interface{}) error {
return utils.NewUnimplementedInterfaceError((Board)(nil), actual)
}
// DependencyTypeError is used when a resource doesn't implement the expected interface.
func DependencyTypeError(name, actual interface{}) error {
return utils.DependencyTypeError(name, (Board)(nil), actual)
}
func init() {
registry.RegisterResourceSubtype(Subtype, registry.ResourceSubtype{
Reconfigurable: WrapWithReconfigurable,
Status: func(ctx context.Context, resource interface{}) (interface{}, error) {
board, ok := resource.(Board)
if !ok {
return nil, NewUnimplementedInterfaceError(resource)
}
return board.Status(ctx, nil)
},
RegisterRPCService: func(ctx context.Context, rpcServer rpc.Server, subtypeSvc subtype.Service) error {
return rpcServer.RegisterServiceServer(
ctx,
&pb.BoardService_ServiceDesc,
NewServer(subtypeSvc),
pb.RegisterBoardServiceHandlerFromEndpoint,
)
},
RPCServiceDesc: &pb.BoardService_ServiceDesc,
RPCClient: func(ctx context.Context, conn rpc.ClientConn, name string, logger golog.Logger) interface{} {
return NewClientFromConn(ctx, conn, name, logger)
},
})
}
// SubtypeName is a constant that identifies the component resource subtype string "board".
const SubtypeName = resource.SubtypeName("board")
// Subtype is a constant that identifies the component resource subtype.
var Subtype = resource.NewSubtype(
resource.ResourceNamespaceRDK,
resource.ResourceTypeComponent,
SubtypeName,
)
// Named is a helper for getting the named board's typed resource name.
func Named(name string) resource.Name {
return resource.NameFromSubtype(Subtype, name)
}
// A Board represents a physical general purpose board that contains various
// components such as analog readers, and digital interrupts.
type Board interface {
// AnalogReaderByName returns an analog reader by name.
AnalogReaderByName(name string) (AnalogReader, bool)
// DigitalInterruptByName returns a digital interrupt by name.
DigitalInterruptByName(name string) (DigitalInterrupt, bool)
// GPIOPinByName returns a GPIOPin by name.
GPIOPinByName(name string) (GPIOPin, error)
// SPINames returns the names of all known SPI buses.
SPINames() []string
// I2CNames returns the names of all known I2C buses.
I2CNames() []string
// AnalogReaderNames returns the name of all known analog readers.
AnalogReaderNames() []string
// DigitalInterruptNames returns the name of all known digital interrupts.
DigitalInterruptNames() []string
// GPIOPinNames returns the names of all known GPIO pins.
GPIOPinNames() []string
// Status returns the current status of the board. Usually you
// should use the CreateStatus helper instead of directly calling
// this.
Status(ctx context.Context, extra map[string]interface{}) (*commonpb.BoardStatus, error)
// ModelAttributes returns attributes related to the model of this board.
ModelAttributes() ModelAttributes
generic.Generic
}
// A LocalBoard represents a Board where you can request SPIs and I2Cs by name.
type LocalBoard interface {
Board
// SPIByName returns an SPI bus by name.
SPIByName(name string) (SPI, bool)
// I2CByName returns an I2C bus by name.
I2CByName(name string) (I2C, bool)
}
// ModelAttributes provide info related to a board model.
type ModelAttributes struct {
// Remote signifies this board is accessed over a remote connection.
// e.g. gRPC
Remote bool
}
// SPI represents a shareable SPI bus on the board.
type SPI interface {
// OpenHandle locks the shared bus and returns a handle interface that MUST be closed when done.
OpenHandle() (SPIHandle, error)
}
// SPIHandle is similar to an io handle. It MUST be closed to release the bus.
type SPIHandle interface {
// Xfer performs a single SPI transfer, that is, the complete transaction from chipselect enable to chipselect disable.
// SPI transfers are synchronous, number of bytes received will be equal to the number of bytes sent.
// Write-only transfers can usually just discard the returned bytes.
// Read-only transfers usually transmit a request/address and continue with some number of null bytes to equal the expected size of the
// returning data.
// Large transmissions are usually broken up into multiple transfers.
// There are many different paradigms for most of the above, and implementation details are chip/device specific.
Xfer(
ctx context.Context,
baud uint,
chipSelect string,
mode uint,
tx []byte,
) ([]byte, error)
// Close closes the handle and releases the lock on the bus.
Close() error
}
// An AnalogReader represents an analog pin reader that resides on a board.
type AnalogReader interface {
// Read reads off the current value.
Read(ctx context.Context, extra map[string]interface{}) (int, error)
}
// A PostProcessor takes a raw input and transforms it into a new value.
// Multiple post processors can be stacked on each other. This is currently
// only used in DigitalInterrupt readings.
type PostProcessor func(raw int64) int64
var (
_ = Board(&reconfigurableBoard{})
_ = LocalBoard(&reconfigurableLocalBoard{})
_ = resource.Reconfigurable(&reconfigurableBoard{})
_ = resource.Reconfigurable(&reconfigurableLocalBoard{})
_ = viamutils.ContextCloser(&reconfigurableLocalBoard{})
)
// FromDependencies is a helper for getting the named board from a collection of
// dependencies.
func FromDependencies(deps registry.Dependencies, name string) (Board, error) {
res, ok := deps[Named(name)]
if !ok {
return nil, utils.DependencyNotFoundError(name)
}
part, ok := res.(Board)
if !ok {
return nil, DependencyTypeError(name, res)
}
return part, nil
}
// FromRobot is a helper for getting the named board from the given Robot.
func FromRobot(r robot.Robot, name string) (Board, error) {
res, err := r.ResourceByName(Named(name))
if err != nil {
return nil, err
}
part, ok := res.(Board)
if !ok {
return nil, NewUnimplementedInterfaceError(res)
}
return part, nil
}
// NamesFromRobot is a helper for getting all board names from the given Robot.
func NamesFromRobot(r robot.Robot) []string {
return robot.NamesBySubtype(r, Subtype)
}
type reconfigurableBoard struct {
mu sync.RWMutex
actual Board
analogs map[string]*reconfigurableAnalogReader
digitals map[string]*reconfigurableDigitalInterrupt
}
func (r *reconfigurableBoard) ProxyFor() interface{} {
r.mu.RLock()
defer r.mu.RUnlock()
return r.actual
}
func (r *reconfigurableBoard) DoCommand(ctx context.Context, cmd map[string]interface{}) (map[string]interface{}, error) {
r.mu.RLock()
defer r.mu.RUnlock()
return r.actual.DoCommand(ctx, cmd)
}
func (r *reconfigurableBoard) AnalogReaderByName(name string) (AnalogReader, bool) {
r.mu.RLock()
defer r.mu.RUnlock()
a, ok := r.analogs[name]
return a, ok
}
func (r *reconfigurableBoard) DigitalInterruptByName(name string) (DigitalInterrupt, bool) {
r.mu.RLock()
defer r.mu.RUnlock()
d, ok := r.digitals[name]
if !ok {
if d, ok := r.actual.DigitalInterruptByName(name); ok {
r.digitals[name] = &reconfigurableDigitalInterrupt{actual: d}
return r.digitals[name], ok
}
}
return d, ok
}
func (r *reconfigurableBoard) GPIOPinByName(name string) (GPIOPin, error) {
r.mu.RLock()
defer r.mu.RUnlock()
return r.actual.GPIOPinByName(name)
}
func (r *reconfigurableBoard) SPINames() []string {
r.mu.RLock()
defer r.mu.RUnlock()
return r.actual.SPINames()
}
func (r *reconfigurableBoard) I2CNames() []string {
r.mu.RLock()
defer r.mu.RUnlock()
return r.actual.I2CNames()
}
func (r *reconfigurableBoard) AnalogReaderNames() []string {
r.mu.RLock()
defer r.mu.RUnlock()
return r.actual.AnalogReaderNames()
}
func (r *reconfigurableBoard) DigitalInterruptNames() []string {
r.mu.RLock()
defer r.mu.RUnlock()
return r.actual.DigitalInterruptNames()
}
func (r *reconfigurableBoard) GPIOPinNames() []string {
r.mu.RLock()
defer r.mu.RUnlock()
return r.actual.GPIOPinNames()
}
func (r *reconfigurableBoard) Status(ctx context.Context, extra map[string]interface{}) (*commonpb.BoardStatus, error) {
r.mu.RLock()
defer r.mu.RUnlock()
if r.actual.ModelAttributes().Remote {
return r.actual.Status(ctx, extra)
}
return CreateStatus(ctx, r, extra)
}
func (r *reconfigurableBoard) Reconfigure(ctx context.Context, newBoard resource.Reconfigurable) error {
r.mu.Lock()
defer r.mu.Unlock()
return r.reconfigure(ctx, newBoard)
}
func (r *reconfigurableBoard) reconfigure(ctx context.Context, newBoard resource.Reconfigurable) error {
actual, ok := newBoard.(*reconfigurableBoard)
if !ok {
return utils.NewUnexpectedTypeError(r, newBoard)
}
if err := viamutils.TryClose(ctx, r.actual); err != nil {
golog.Global().Errorw("error closing old", "error", err)
}
var oldAnalogReaderNames map[string]struct{}
var oldDigitalInterruptNames map[string]struct{}
if len(r.analogs) != 0 {
oldAnalogReaderNames = make(map[string]struct{}, len(r.analogs))
for name := range r.analogs {
oldAnalogReaderNames[name] = struct{}{}
}
}
if len(r.digitals) != 0 {
oldDigitalInterruptNames = make(map[string]struct{}, len(r.digitals))
for name := range r.digitals {
oldDigitalInterruptNames[name] = struct{}{}
}
}
for name, newPart := range actual.analogs {
oldPart, ok := r.analogs[name]
delete(oldAnalogReaderNames, name)
if ok {
oldPart.reconfigure(ctx, newPart)
continue
}
r.analogs[name] = newPart
}
for name, newPart := range actual.digitals {
oldPart, ok := r.digitals[name]
delete(oldDigitalInterruptNames, name)
if ok {
oldPart.reconfigure(ctx, newPart)
continue
}
r.digitals[name] = newPart
}
for name := range oldAnalogReaderNames {
delete(r.analogs, name)
}
for name := range oldDigitalInterruptNames {
delete(r.digitals, name)
}
r.actual = actual.actual
return nil
}
func (r *reconfigurableBoard) ModelAttributes() ModelAttributes {
r.mu.RLock()
defer r.mu.RUnlock()
return r.actual.ModelAttributes()
}
// Close attempts to cleanly close each part of the board.
func (r *reconfigurableBoard) Close(ctx context.Context) error {
r.mu.RLock()
defer r.mu.RUnlock()
return viamutils.TryClose(ctx, r.actual)
}
// UpdateAction helps hinting the reconfiguration process on what strategy to use given a modified config.
// See config.UpdateActionType for more information.
func (r *reconfigurableBoard) UpdateAction(c *config.Component) config.UpdateActionType {
obj, canUpdate := r.actual.(interface {
UpdateAction(config *config.Component) config.UpdateActionType
})
if canUpdate {
return obj.UpdateAction(c)
}
return config.Reconfigure
}
type reconfigurableLocalBoard struct {
*reconfigurableBoard
actual LocalBoard
spis map[string]*reconfigurableSPI
i2cs map[string]*reconfigurableI2C
}
func (r *reconfigurableLocalBoard) SPIByName(name string) (SPI, bool) {
r.mu.RLock()
defer r.mu.RUnlock()
s, ok := r.spis[name]
return s, ok
}
func (r *reconfigurableLocalBoard) I2CByName(name string) (I2C, bool) {
r.mu.RLock()
defer r.mu.RUnlock()
s, ok := r.i2cs[name]
return s, ok
}
func (r *reconfigurableLocalBoard) Reconfigure(ctx context.Context, newBoard resource.Reconfigurable) error {
r.mu.Lock()
defer r.mu.Unlock()
actual, ok := newBoard.(*reconfigurableLocalBoard)
if !ok {
return utils.NewUnexpectedTypeError(r, newBoard)
}
if err := viamutils.TryClose(ctx, r.actual); err != nil {
golog.Global().Errorw("error closing old", "error", err)
}
var oldSPINames map[string]struct{}
var oldI2CNames map[string]struct{}
if len(r.spis) != 0 {
oldSPINames = make(map[string]struct{}, len(r.spis))
for name := range r.spis {
oldSPINames[name] = struct{}{}
}
}
if len(r.i2cs) != 0 {
oldI2CNames = make(map[string]struct{}, len(r.i2cs))
for name := range r.i2cs {
oldI2CNames[name] = struct{}{}
}
}
for name, newPart := range actual.spis {
oldPart, ok := r.spis[name]
delete(oldSPINames, name)
if ok {
oldPart.reconfigure(ctx, newPart)
continue
}
r.spis[name] = newPart
}
for name, newPart := range actual.i2cs {
oldPart, ok := r.i2cs[name]
delete(oldI2CNames, name)
if ok {
oldPart.reconfigure(ctx, newPart)
continue
}
r.i2cs[name] = newPart
}
for name := range oldSPINames {
delete(r.spis, name)
}
for name := range oldI2CNames {
delete(r.i2cs, name)
}
r.actual = actual.actual
return r.reconfigurableBoard.reconfigure(ctx, actual.reconfigurableBoard)
}
// WrapWithReconfigurable converts a regular Board implementation to a reconfigurableBoard.
// If board is already a reconfigurableBoard, then nothing is done.
func WrapWithReconfigurable(r interface{}) (resource.Reconfigurable, error) {
board, ok := r.(Board)
if !ok {
return nil, NewUnimplementedInterfaceError(r)
}
if reconfigurable, ok := board.(*reconfigurableBoard); ok {
return reconfigurable, nil
}
rb := reconfigurableBoard{
actual: board,
analogs: map[string]*reconfigurableAnalogReader{},
digitals: map[string]*reconfigurableDigitalInterrupt{},
}
for _, name := range rb.actual.AnalogReaderNames() {
actualPart, ok := rb.actual.AnalogReaderByName(name)
if !ok {
continue
}
rb.analogs[name] = &reconfigurableAnalogReader{actual: actualPart}
}
for _, name := range rb.actual.DigitalInterruptNames() {
actualPart, ok := rb.actual.DigitalInterruptByName(name)
if !ok {
continue
}
rb.digitals[name] = &reconfigurableDigitalInterrupt{actual: actualPart}
}
localBoard, ok := r.(LocalBoard)
if !ok {
return &rb, nil
}
if reconfigurable, ok := localBoard.(*reconfigurableLocalBoard); ok {
return reconfigurable, nil
}
rlb := reconfigurableLocalBoard{
actual: localBoard,
spis: map[string]*reconfigurableSPI{},
i2cs: map[string]*reconfigurableI2C{},
reconfigurableBoard: &rb,
}
for _, name := range rlb.actual.SPINames() {
actualPart, ok := rlb.actual.SPIByName(name)
if !ok {
continue
}
rlb.spis[name] = &reconfigurableSPI{actual: actualPart}
}
for _, name := range rlb.actual.I2CNames() {
actualPart, ok := rlb.actual.I2CByName(name)
if !ok {
continue
}
rlb.i2cs[name] = &reconfigurableI2C{actual: actualPart}
}
return &rlb, nil
}
type reconfigurableSPI struct {
mu sync.RWMutex
actual SPI
}
func (r *reconfigurableSPI) reconfigure(ctx context.Context, newSPI SPI) {
r.mu.Lock()
defer r.mu.Unlock()
actual, ok := newSPI.(*reconfigurableSPI)
if !ok {
panic(utils.NewUnexpectedTypeError(r, newSPI))
}
if err := viamutils.TryClose(ctx, r.actual); err != nil {
golog.Global().Errorw("error closing old", "error", err)
}
r.actual = actual.actual
}
func (r *reconfigurableSPI) OpenHandle() (SPIHandle, error) {
return r.actual.OpenHandle()
}
type reconfigurableI2C struct {
mu sync.RWMutex
actual I2C
}
func (r *reconfigurableI2C) ProxyFor() interface{} {
r.mu.RLock()
defer r.mu.RUnlock()
return r.actual
}
func (r *reconfigurableI2C) reconfigure(ctx context.Context, newI2C I2C) {
r.mu.Lock()
defer r.mu.Unlock()
actual, ok := newI2C.(*reconfigurableI2C)
if !ok {
panic(utils.NewUnexpectedTypeError(r, newI2C))
}
if err := viamutils.TryClose(ctx, r.actual); err != nil {
golog.Global().Errorw("error closing old", "error", err)
}
r.actual = actual.actual
}
func (r *reconfigurableI2C) OpenHandle(addr byte) (I2CHandle, error) {
return r.actual.OpenHandle(addr)
}
type reconfigurableAnalogReader struct {
mu sync.RWMutex
actual AnalogReader
}
func (r *reconfigurableAnalogReader) reconfigure(ctx context.Context, newAnalogReader AnalogReader) {
r.mu.Lock()
defer r.mu.Unlock()
actual, ok := newAnalogReader.(*reconfigurableAnalogReader)
if !ok {
panic(utils.NewUnexpectedTypeError(r, newAnalogReader))
}
if err := viamutils.TryClose(ctx, r.actual); err != nil {
golog.Global().Errorw("error closing old", "error", err)
}
r.actual = actual.actual
}
func (r *reconfigurableAnalogReader) Read(ctx context.Context, extra map[string]interface{}) (int, error) {
r.mu.RLock()
defer r.mu.RUnlock()
return r.actual.Read(ctx, extra)
}
func (r *reconfigurableAnalogReader) ProxyFor() interface{} {
r.mu.RLock()
defer r.mu.RUnlock()
return r.actual
}
func (r *reconfigurableAnalogReader) Close(ctx context.Context) error {
return viamutils.TryClose(ctx, r.actual)
}
type reconfigurableDigitalInterrupt struct {
mu sync.RWMutex
actual DigitalInterrupt
}
func (r *reconfigurableDigitalInterrupt) ProxyFor() interface{} {
r.mu.RLock()
defer r.mu.RUnlock()
return r.actual
}
func (r *reconfigurableDigitalInterrupt) reconfigure(ctx context.Context, newDigitalInterrupt DigitalInterrupt) {
r.mu.Lock()
defer r.mu.Unlock()
actual, ok := newDigitalInterrupt.(*reconfigurableDigitalInterrupt)
if !ok {
panic(utils.NewUnexpectedTypeError(r, newDigitalInterrupt))
}
if err := viamutils.TryClose(ctx, r.actual); err != nil {
golog.Global().Errorw("error closing old", "error", err)
}
r.actual = actual.actual
}
func (r *reconfigurableDigitalInterrupt) Value(ctx context.Context, extra map[string]interface{}) (int64, error) {
r.mu.RLock()
defer r.mu.RUnlock()
return r.actual.Value(ctx, extra)
}
func (r *reconfigurableDigitalInterrupt) Tick(ctx context.Context, high bool, nanos uint64) error {
r.mu.RLock()
defer r.mu.RUnlock()
return r.actual.Tick(ctx, high, nanos)
}
func (r *reconfigurableDigitalInterrupt) AddCallback(c chan bool) {
r.mu.RLock()
defer r.mu.RUnlock()
r.actual.AddCallback(c)
}
func (r *reconfigurableDigitalInterrupt) RemoveCallback(c chan bool) {
r.mu.RLock()
defer r.mu.RUnlock()
r.actual.RemoveCallback(c)
}
func (r *reconfigurableDigitalInterrupt) AddPostProcessor(pp PostProcessor) {
r.mu.RLock()
defer r.mu.RUnlock()
r.actual.AddPostProcessor(pp)
}
func (r *reconfigurableDigitalInterrupt) Close(ctx context.Context) error {
r.mu.RLock()
defer r.mu.RUnlock()
return viamutils.TryClose(ctx, r.actual)
}