-
Notifications
You must be signed in to change notification settings - Fork 24
/
Copy pathclient.go
222 lines (189 loc) · 5.87 KB
/
client.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
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
// Copyright 2014 Krishna Raman
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package firmata
import (
"fmt"
"github.com/tarm/serial"
"io"
"log"
"os"
"time"
)
// Arduino Firmata client for golang
type FirmataClient struct {
serialDev string
baud int
conn *io.ReadWriteCloser
Log *log.Logger
protocolVersion []byte
firmwareVersion []int
firmwareName string
ready bool
analogMappingDone bool
capabilityDone bool
digitalPinState [8]byte
analogPinsChannelMap map[int]byte
analogChannelPinsMap map[byte]int
pinModes []map[PinMode]interface{}
valueChan chan FirmataValue
serialChan chan string
spiChan chan []byte
Verbose bool
}
// Creates a new FirmataClient object and connects to the Arduino board
// over specified serial port. This function blocks till a connection is
// succesfullt established and pin mappings are retrieved.
func NewClient(dev string, baud int) (client *FirmataClient, err error) {
var conn io.ReadWriteCloser
c := &serial.Config{Name: dev, Baud: baud}
conn, err = serial.OpenPort(c)
if err != nil {
return nil, err
}
client = &FirmataClient{
serialDev: dev,
baud: baud,
conn: &conn,
Log: log.New(os.Stdout, "[go-firmata] ", log.Ltime),
}
go client.replyReader()
conn.Write([]byte{byte(SystemReset)})
t := time.NewTicker(time.Second)
for !(client.ready && client.analogMappingDone && client.capabilityDone) {
select {
case <-t.C:
//no-op
case <-time.After(time.Second * 15):
client.Log.Print("No response in 30 seconds. Resetting arduino")
conn.Write([]byte{byte(SystemReset)})
case <-time.After(time.Second * 30):
client.Log.Print("Unable to initialize connection")
conn.Close()
client = nil
}
}
client.Log.Print("Client ready to use")
return
}
// Close the serial connection to properly clean up after ourselves
// Usage: defer client.Close()
func (c *FirmataClient) Delay(duration time.Duration) {
time.Sleep(duration)
}
// Close the serial connection to properly clean up after ourselves
// Usage: defer client.Close()
func (c *FirmataClient) Close() {
(*c.conn).Close()
}
// Sets the Pin mode (input, output, etc.) for the Arduino pin
func (c *FirmataClient) SetPinMode(pin uint8, mode PinMode) error {
if c.pinModes[pin][mode] == nil {
return fmt.Errorf("Pin mode %v not supported by pin %v", mode, pin)
}
cmd := []byte{byte(SetPinMode), (pin & 0x7F), byte(mode)}
if err := c.sendCommand(cmd); err != nil {
return err
}
c.Log.Printf("SetPinMode: pin %d -> %s\r\n", pin, mode)
return nil
}
// Specified if a digital Pin should be watched for input.
// Values will be streamed back over a channel which can be retrieved by the GetValues() call
func (c *FirmataClient) EnableDigitalInput(pin uint, val bool) (err error) {
if pin < 0 || pin > uint(len(c.pinModes)) {
err = fmt.Errorf("Invalid pin number %v\n", pin)
return
}
port := (pin / 8) & 0x7F
pin = pin % 8
if val {
cmd := []byte{byte(EnableDigitalInput) | byte(port), 0x01}
err = c.sendCommand(cmd)
} else {
cmd := []byte{byte(EnableDigitalInput) | byte(port), 0x00}
err = c.sendCommand(cmd)
}
return
}
// Set the value of a digital pin
func (c *FirmataClient) DigitalWrite(pin uint8, val bool) error {
if pin < 0 || pin > uint8(len(c.pinModes)) && c.pinModes[pin][Output] != nil {
return fmt.Errorf("Invalid pin number %v\n", pin)
}
port := (pin / 8) & 0x7F
portData := &c.digitalPinState[port]
pin = pin % 8
if val {
(*portData) = (*portData) | (1 << pin)
} else {
(*portData) = (*portData) & ^(1 << pin)
}
data := to7Bit(*(portData))
cmd := []byte{byte(DigitalMessage) | byte(port), data[0], data[1]}
if err := c.sendCommand(cmd); err != nil {
return err
}
c.Log.Printf("DigitalWrite: pin %d -> %t\r\n", pin, val)
return nil
}
// Specified if a analog Pin should be watched for input.
// Values will be streamed back over a channel which can be retrieved by the GetValues() call
func (c *FirmataClient) EnableAnalogInput(pin uint, val bool) (err error) {
if pin < 0 || pin > uint(len(c.pinModes)) && c.pinModes[pin][Analog] != nil {
err = fmt.Errorf("Invalid pin number %v\n", pin)
return
}
ch := byte(c.analogPinsChannelMap[int(pin)])
c.Log.Printf("Enable analog inout on pin %v channel %v", pin, ch)
if val {
cmd := []byte{byte(EnableAnalogInput) | ch, 0x01}
err = c.sendCommand(cmd)
} else {
cmd := []byte{byte(EnableAnalogInput) | ch, 0x00}
err = c.sendCommand(cmd)
}
return
}
// Set the value of a analog pin
func (c *FirmataClient) AnalogWrite(pin uint, pinData byte) (err error) {
if pin < 0 || pin > uint(len(c.pinModes)) && c.pinModes[pin][Analog] != nil {
err = fmt.Errorf("Invalid pin number %v\n", pin)
return
}
data := to7Bit(pinData)
cmd := []byte{byte(AnalogMessage) | byte(pin), data[0], data[1]}
err = c.sendCommand(cmd)
return
}
func (c *FirmataClient) sendCommand(cmd []byte) (err error) {
bStr := ""
for _, b := range cmd {
bStr = bStr + fmt.Sprintf(" %#2x", b)
}
if c.Verbose {
c.Log.Printf("Command send%v\n", bStr)
}
_, err = (*c.conn).Write(cmd)
return
}
// Sets the polling interval in milliseconds for analog pin samples
func (c *FirmataClient) SetAnalogSamplingInterval(ms byte) (err error) {
data := to7Bit(ms)
err = c.sendSysEx(SamplingInterval, data[0], data[1])
return
}
// Get the channel to retrieve analog and digital pin values
func (c *FirmataClient) GetValues() <-chan FirmataValue {
return c.valueChan
}