forked from hybridgroup/gobot
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmegapi_adaptor.go
85 lines (74 loc) · 1.92 KB
/
megapi_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
80
81
82
83
84
85
package megapi
import (
"io"
"time"
serial "go.bug.st/serial.v1"
"gobot.io/x/gobot"
)
var _ gobot.Adaptor = (*Adaptor)(nil)
// Adaptor is the Gobot adaptor for the MakeBlock MegaPi board
type Adaptor struct {
name string
port string
connection io.ReadWriteCloser
serialMode *serial.Mode
writeBytesChannel chan []byte
finalizeChannel chan struct{}
}
// NewAdaptor returns a new MegaPi Adaptor with specified serial port used to talk to the MegaPi with a baud rate of 115200
func NewAdaptor(device string) *Adaptor {
c := &serial.Mode{BaudRate: 115200}
return &Adaptor{
name: "MegaPi",
connection: nil,
port: device,
serialMode: c,
writeBytesChannel: make(chan []byte),
finalizeChannel: make(chan struct{}),
}
}
// Name returns the name of this adaptor
func (megaPi *Adaptor) Name() string {
return megaPi.name
}
// SetName sets the name of this adaptor
func (megaPi *Adaptor) SetName(n string) {
megaPi.name = n
}
// Connect starts a connection to the board
func (megaPi *Adaptor) Connect() error {
if megaPi.connection == nil {
sp, err := serial.Open(megaPi.port, megaPi.serialMode)
if err != nil {
return err
}
// sleeping is required to give the board a chance to reset
time.Sleep(2 * time.Second)
megaPi.connection = sp
}
// kick off thread to send bytes to the board
go func() {
for {
select {
case bytes := <-megaPi.writeBytesChannel:
megaPi.connection.Write(bytes)
time.Sleep(10 * time.Millisecond)
case <-megaPi.finalizeChannel:
megaPi.finalizeChannel <- struct{}{}
return
default:
time.Sleep(10 * time.Millisecond)
}
}
}()
return nil
}
// Finalize terminates the connection to the board
func (megaPi *Adaptor) Finalize() error {
megaPi.finalizeChannel <- struct{}{}
<-megaPi.finalizeChannel
if err := megaPi.connection.Close(); err != nil {
return err
}
return nil
}