forked from hybridgroup/gobot
-
Notifications
You must be signed in to change notification settings - Fork 0
/
device.go
131 lines (110 loc) · 2.52 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
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
package gobot
import (
"errors"
"fmt"
"log"
"reflect"
"time"
)
type Device interface {
Start() bool
Halt() bool
setInterval(time.Duration)
interval() time.Duration
setName(string)
name() string
adaptor() AdaptorInterface
commands() map[string]func(map[string]interface{}) interface{}
}
type JSONDevice struct {
Name string `json:"name"`
Driver string `json:"driver"`
Connection *JSONConnection `json:"connection"`
Commands []string `json:"commands"`
}
type device struct {
Name string
Type string
Robot *Robot
Driver DriverInterface
}
type devices []*device
// Start() starts all the devices.
func (d devices) Start() error {
var err error
log.Println("Starting devices...")
for _, device := range d {
log.Println("Starting device " + device.Name + "...")
if device.Start() == false {
err = errors.New("Could not start device")
break
}
}
return err
}
// Halt() stop all the devices.
func (d devices) Halt() {
for _, device := range d {
device.Halt()
}
}
func NewDevice(driver DriverInterface, r *Robot) *device {
if driver.name() == "" {
driver.setName(fmt.Sprintf("%X", Rand(int(^uint(0)>>1))))
}
t := reflect.ValueOf(driver).Type().String()
if driver.interval() == 0 {
driver.setInterval(10 * time.Millisecond)
}
return &device{
Type: t[1:len(t)],
Name: driver.name(),
Robot: r,
Driver: driver,
}
}
func (d *device) adaptor() AdaptorInterface {
return d.Driver.adaptor()
}
func (d *device) setInterval(t time.Duration) {
d.Driver.setInterval(t)
}
func (d *device) interval() time.Duration {
return d.Driver.interval()
}
func (d *device) setName(s string) {
d.Name = s
}
func (d *device) name() string {
return d.Name
}
func (d *device) commands() map[string]func(map[string]interface{}) interface{} {
return d.Driver.commands()
}
func (d *device) Commands() map[string]func(map[string]interface{}) interface{} {
return d.commands()
}
func (d *device) Start() bool {
log.Println("Device " + d.Name + " started")
return d.Driver.Start()
}
func (d *device) Halt() bool {
log.Println("Device " + d.Name + " halted")
return d.Driver.Halt()
}
func (d *device) ToJSON() *JSONDevice {
jsonDevice := &JSONDevice{
Name: d.Name,
Driver: d.Type,
Commands: []string{},
Connection: nil,
}
if d.adaptor() != nil {
jsonDevice.Connection = d.Robot.Connection(d.adaptor().name()).ToJSON()
}
commands := d.commands()
for command := range commands {
jsonDevice.Commands = append(jsonDevice.Commands, command)
}
return jsonDevice
}