forked from hybridgroup/gobot
-
Notifications
You must be signed in to change notification settings - Fork 0
/
device.go
84 lines (73 loc) · 1.77 KB
/
device.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
package gobot
import (
"errors"
"fmt"
"log"
"reflect"
)
// JSONDevice is a JSON representation of a Gobot Device.
type JSONDevice struct {
Name string `json:"name"`
Driver string `json:"driver"`
Connection string `json:"connection"`
Commands []string `json:"commands"`
}
func NewJSONDevice(device Device) *JSONDevice {
jsonDevice := &JSONDevice{
Name: device.Name(),
Driver: reflect.TypeOf(device).String(),
Commands: []string{},
Connection: "",
}
if device.Connection() != nil {
jsonDevice.Connection = device.Connection().Name()
}
if commander, ok := device.(Commander); ok {
for command := range commander.Commands() {
jsonDevice.Commands = append(jsonDevice.Commands, command)
}
}
return jsonDevice
}
type Device Driver
type devices []Device
// Len returns devices length
func (d *devices) Len() int {
return len(*d)
}
// Each calls `f` function each device
func (d *devices) Each(f func(Device)) {
for _, device := range *d {
f(device)
}
}
// Start starts all the devices.
func (d *devices) Start() (errs []error) {
log.Println("Starting devices...")
for _, device := range *d {
info := "Starting device " + device.Name()
if pinner, ok := device.(Pinner); ok {
info = info + " on pin " + pinner.Pin()
}
log.Println(info + "...")
if errs = device.Start(); len(errs) > 0 {
for i, err := range errs {
errs[i] = errors.New(fmt.Sprintf("Device %q: %v", device.Name(), err))
}
return
}
}
return
}
// Halt stop all the devices.
func (d *devices) Halt() (errs []error) {
for _, device := range *d {
if derrs := device.Halt(); len(derrs) > 0 {
for i, err := range derrs {
derrs[i] = errors.New(fmt.Sprintf("Device %q: %v", device.Name(), err))
}
errs = append(errs, derrs...)
}
}
return
}