forked from hybridgroup/gobot
-
Notifications
You must be signed in to change notification settings - Fork 0
/
driver.go
89 lines (74 loc) · 1.7 KB
/
driver.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
package gobot
import (
"fmt"
"time"
)
type Driver struct {
Adaptor AdaptorInterface
Interval time.Duration
Pin string
Name string
commands map[string]func(map[string]interface{}) interface{}
Events map[string]*Event
Type string
}
type DriverInterface interface {
Start() bool
Halt() bool
adaptor() AdaptorInterface
setInterval(time.Duration)
interval() time.Duration
setName(string)
name() string
Commands() map[string]func(map[string]interface{}) interface{}
ToJSON() *JSONDevice
}
func (d *Driver) adaptor() AdaptorInterface {
return d.Adaptor
}
func (d *Driver) setInterval(t time.Duration) {
d.Interval = t
}
func (d *Driver) interval() time.Duration {
return d.Interval
}
func (d *Driver) setName(s string) {
d.Name = s
}
func (d *Driver) name() string {
return d.Name
}
func (d *Driver) Commands() map[string]func(map[string]interface{}) interface{} {
return d.commands
}
func (d *Driver) AddCommand(name string, f func(map[string]interface{}) interface{}) {
d.Commands()[name] = f
}
func NewDriver(name string, t string, a AdaptorInterface) *Driver {
if name == "" {
name = fmt.Sprintf("%X", Rand(int(^uint(0)>>1)))
}
return &Driver{
Type: t,
Name: name,
Interval: 10 * time.Millisecond,
commands: make(map[string]func(map[string]interface{}) interface{}),
Adaptor: a,
}
}
func (d *Driver) ToJSON() *JSONDevice {
jsonDevice := &JSONDevice{
Name: d.Name,
Driver: d.Type,
Commands: []string{},
Connection: nil,
}
if d.adaptor() != nil {
jsonDevice.Connection = d.adaptor().ToJSON()
}
commands := d.Commands()
for command := range commands {
jsonDevice.Commands = append(jsonDevice.Commands, command)
}
return jsonDevice
}