forked from hybridgroup/gobot
-
Notifications
You must be signed in to change notification settings - Fork 0
/
sphero_adaptor.go
79 lines (65 loc) · 1.78 KB
/
sphero_adaptor.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
package sphero
import (
"io"
"gobot.io/x/gobot"
serial "go.bug.st/serial.v1"
)
// Adaptor represents a Connection to a Sphero
type Adaptor struct {
name string
port string
sp io.ReadWriteCloser
connected bool
connect func(string) (io.ReadWriteCloser, error)
}
// NewAdaptor returns a new Sphero Adaptor given a port
func NewAdaptor(port string) *Adaptor {
return &Adaptor{
name: gobot.DefaultName("Sphero"),
port: port,
connect: func(port string) (io.ReadWriteCloser, error) {
return serial.Open(port, &serial.Mode{BaudRate: 115200})
},
}
}
// Name returns the Adaptor's name
func (a *Adaptor) Name() string { return a.name }
// SetName sets the Adaptor's name
func (a *Adaptor) SetName(n string) { a.name = n }
// Port returns the Adaptor's port
func (a *Adaptor) Port() string { return a.port }
// SetPort sets the Adaptor's port
func (a *Adaptor) SetPort(p string) { a.port = p }
// Connect initiates a connection to the Sphero. Returns true on successful connection.
func (a *Adaptor) Connect() (err error) {
sp, e := a.connect(a.Port())
if e != nil {
return e
}
a.sp = sp
a.connected = true
return
}
// Reconnect attempts to reconnect to the Sphero. If the Sphero has an active connection
// it will first close that connection and then establish a new connection.
// Returns true on Successful reconnection
func (a *Adaptor) Reconnect() (err error) {
if a.connected {
a.Disconnect()
}
return a.Connect()
}
// Disconnect terminates the connection to the Sphero. Returns true on successful disconnect.
func (a *Adaptor) Disconnect() error {
if a.connected {
if e := a.sp.Close(); e != nil {
return e
}
a.connected = false
}
return nil
}
// Finalize finalizes the Sphero Adaptor
func (a *Adaptor) Finalize() error {
return a.Disconnect()
}