forked from hybridgroup/gobot
-
Notifications
You must be signed in to change notification settings - Fork 0
/
client.go
477 lines (416 loc) · 11.8 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
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
// Package client provies a client for interacting with microcontrollers
// using the Firmata protocol https://github.com/firmata/protocol.
package client
import (
"errors"
"fmt"
"io"
"math"
"time"
"github.com/hybridgroup/gobot"
)
// Pin Modes
const (
Input = 0x00
Output = 0x01
Analog = 0x02
Pwm = 0x03
Servo = 0x04
)
// Sysex Codes
const (
ProtocolVersion byte = 0xF9
SystemReset byte = 0xFF
DigitalMessage byte = 0x90
DigitalMessageRangeStart byte = 0x90
DigitalMessageRangeEnd byte = 0x9F
AnalogMessage byte = 0xE0
AnalogMessageRangeStart byte = 0xE0
AnalogMessageRangeEnd byte = 0xEF
ReportAnalog byte = 0xC0
ReportDigital byte = 0xD0
PinMode byte = 0xF4
StartSysex byte = 0xF0
EndSysex byte = 0xF7
CapabilityQuery byte = 0x6B
CapabilityResponse byte = 0x6C
PinStateQuery byte = 0x6D
PinStateResponse byte = 0x6E
AnalogMappingQuery byte = 0x69
AnalogMappingResponse byte = 0x6A
StringData byte = 0x71
I2CRequest byte = 0x76
I2CReply byte = 0x77
I2CConfig byte = 0x78
FirmwareQuery byte = 0x79
I2CModeWrite byte = 0x00
I2CModeRead byte = 0x01
I2CModeContinuousRead byte = 0x02
I2CModeStopReading byte = 0x03
ServoConfig byte = 0x70
)
// Errors
var (
ErrConnected = errors.New("client is already connected")
)
// Client represents a client connection to a firmata board
type Client struct {
pins []Pin
FirmwareName string
ProtocolVersion string
connected bool
connection io.ReadWriteCloser
analogPins []int
initTimeInterval time.Duration
gobot.Eventer
}
// Pin represents a pin on the firmata board
type Pin struct {
SupportedModes []int
Mode int
Value int
State int
AnalogChannel int
}
// I2cReply represents the response from an I2cReply message
type I2cReply struct {
Address int
Register int
Data []byte
}
// New returns a new Client
func New() *Client {
c := &Client{
ProtocolVersion: "",
FirmwareName: "",
connection: nil,
pins: []Pin{},
analogPins: []int{},
connected: false,
Eventer: gobot.NewEventer(),
}
for _, s := range []string{
"FirmwareQuery",
"CapabilityQuery",
"AnalogMappingQuery",
"ProtocolVersion",
"I2cReply",
"StringData",
"Error",
} {
c.AddEvent(s)
}
return c
}
// Disconnect disconnects the Client
func (b *Client) Disconnect() (err error) {
b.connected = false
return b.connection.Close()
}
// Connected returns the current connection state of the Client
func (b *Client) Connected() bool {
return b.connected
}
// Pins returns all available pins
func (b *Client) Pins() []Pin {
return b.pins
}
// Connect connects to the Client given conn. It first resets the firmata board
// then continuously polls the firmata board for new information when it's
// available.
func (b *Client) Connect(conn io.ReadWriteCloser) (err error) {
if b.connected {
return ErrConnected
}
b.connection = conn
b.Reset()
initFunc := b.ProtocolVersionQuery
gobot.Once(b.Event("ProtocolVersion"), func(data interface{}) {
initFunc = b.FirmwareQuery
})
gobot.Once(b.Event("FirmwareQuery"), func(data interface{}) {
initFunc = b.CapabilitiesQuery
})
gobot.Once(b.Event("CapabilityQuery"), func(data interface{}) {
initFunc = b.AnalogMappingQuery
})
gobot.Once(b.Event("AnalogMappingQuery"), func(data interface{}) {
initFunc = func() error { return nil }
b.ReportDigital(0, 1)
b.ReportDigital(1, 1)
b.connected = true
})
for {
if err := initFunc(); err != nil {
return err
}
if err := b.process(); err != nil {
return err
}
if b.connected {
go func() {
for {
if !b.connected {
break
}
if err := b.process(); err != nil {
gobot.Publish(b.Event("Error"), err)
}
}
}()
break
}
}
return
}
// Reset sends the SystemReset sysex code.
func (b *Client) Reset() error {
return b.write([]byte{SystemReset})
}
// SetPinMode sets the pin to mode.
func (b *Client) SetPinMode(pin int, mode int) error {
b.pins[byte(pin)].Mode = mode
return b.write([]byte{PinMode, byte(pin), byte(mode)})
}
// DigitalWrite writes value to pin.
func (b *Client) DigitalWrite(pin int, value int) error {
port := byte(math.Floor(float64(pin) / 8))
portValue := byte(0)
b.pins[pin].Value = value
for i := byte(0); i < 8; i++ {
if b.pins[8*port+i].Value != 0 {
portValue = portValue | (1 << i)
}
}
return b.write([]byte{DigitalMessage | port, portValue & 0x7F, (portValue >> 7) & 0x7F})
}
// ServoConfig sets the min and max pulse width for servo PWM range
func (b *Client) ServoConfig(pin int, max int, min int) error {
ret := []byte{
ServoConfig,
byte(pin),
byte(max & 0x7F),
byte((max >> 7) & 0x7F),
byte(min & 0x7F),
byte((min >> 7) & 0x7F),
}
return b.writeSysex(ret)
}
// AnalogWrite writes value to pin.
func (b *Client) AnalogWrite(pin int, value int) error {
b.pins[pin].Value = value
return b.write([]byte{AnalogMessage | byte(pin), byte(value & 0x7F), byte((value >> 7) & 0x7F)})
}
// FirmwareQuery sends the FirmwareQuery sysex code.
func (b *Client) FirmwareQuery() error {
return b.writeSysex([]byte{FirmwareQuery})
}
// PinStateQuery sends a PinStateQuery for pin.
func (b *Client) PinStateQuery(pin int) error {
return b.writeSysex([]byte{PinStateQuery, byte(pin)})
}
// ProtocolVersionQuery sends the ProtocolVersion sysex code.
func (b *Client) ProtocolVersionQuery() error {
return b.write([]byte{ProtocolVersion})
}
// CapabilitiesQuery sends the CapabilityQuery sysex code.
func (b *Client) CapabilitiesQuery() error {
return b.writeSysex([]byte{CapabilityQuery})
}
// AnalogMappingQuery sends the AnalogMappingQuery sysex code.
func (b *Client) AnalogMappingQuery() error {
return b.writeSysex([]byte{AnalogMappingQuery})
}
// ReportDigital enables or disables digital reporting for pin, a non zero
// state enables reporting
func (b *Client) ReportDigital(pin int, state int) error {
return b.togglePinReporting(pin, state, ReportDigital)
}
// ReportAnalog enables or disables analog reporting for pin, a non zero
// state enables reporting
func (b *Client) ReportAnalog(pin int, state int) error {
return b.togglePinReporting(pin, state, ReportAnalog)
}
// I2cRead reads numBytes from address once.
func (b *Client) I2cRead(address int, numBytes int) error {
return b.writeSysex([]byte{I2CRequest, byte(address), (I2CModeRead << 3),
byte(numBytes) & 0x7F, (byte(numBytes) >> 7) & 0x7F})
}
// I2cWrite writes data to address.
func (b *Client) I2cWrite(address int, data []byte) error {
ret := []byte{I2CRequest, byte(address), (I2CModeWrite << 3)}
for _, val := range data {
ret = append(ret, byte(val&0x7F))
ret = append(ret, byte((val>>7)&0x7F))
}
return b.writeSysex(ret)
}
// I2cConfig configures the delay in which a register can be read from after it
// has been written to.
func (b *Client) I2cConfig(delay int) error {
return b.writeSysex([]byte{I2CConfig, byte(delay & 0xFF), byte((delay >> 8) & 0xFF)})
}
func (b *Client) togglePinReporting(pin int, state int, mode byte) error {
if state != 0 {
state = 1
} else {
state = 0
}
if err := b.write([]byte{byte(mode) | byte(pin), byte(state)}); err != nil {
return err
}
return nil
}
func (b *Client) writeSysex(data []byte) (err error) {
return b.write(append([]byte{StartSysex}, append(data, EndSysex)...))
}
func (b *Client) write(data []byte) (err error) {
_, err = b.connection.Write(data[:])
return
}
func (b *Client) read(length int) (buf []byte, err error) {
i := 0
for length > 0 {
tmp := make([]byte, length)
if i, err = b.connection.Read(tmp); err != nil {
if err.Error() != "EOF" {
return
}
<-time.After(5 * time.Millisecond)
}
if i > 0 {
buf = append(buf, tmp...)
length = length - i
}
}
return
}
func (b *Client) process() (err error) {
buf, err := b.read(3)
if err != nil {
return err
}
messageType := buf[0]
switch {
case ProtocolVersion == messageType:
b.ProtocolVersion = fmt.Sprintf("%v.%v", buf[1], buf[2])
gobot.Publish(b.Event("ProtocolVersion"), b.ProtocolVersion)
case AnalogMessageRangeStart <= messageType &&
AnalogMessageRangeEnd >= messageType:
value := uint(buf[1]) | uint(buf[2])<<7
pin := int((messageType & 0x0F))
if len(b.analogPins) > pin {
if len(b.pins) > b.analogPins[pin] {
b.pins[b.analogPins[pin]].Value = int(value)
gobot.Publish(b.Event(fmt.Sprintf("AnalogRead%v", pin)), b.pins[b.analogPins[pin]].Value)
}
}
case DigitalMessageRangeStart <= messageType &&
DigitalMessageRangeEnd >= messageType:
port := messageType & 0x0F
portValue := buf[1] | (buf[2] << 7)
for i := 0; i < 8; i++ {
pinNumber := int((8*byte(port) + byte(i)))
if len(b.pins) > pinNumber {
if b.pins[pinNumber].Mode == Input {
b.pins[pinNumber].Value = int((portValue >> (byte(i) & 0x07)) & 0x01)
gobot.Publish(b.Event(fmt.Sprintf("DigitalRead%v", pinNumber)), b.pins[pinNumber].Value)
}
}
}
case StartSysex == messageType:
currentBuffer := buf
for {
buf, err = b.read(1)
if err != nil {
return err
}
currentBuffer = append(currentBuffer, buf[0])
if buf[0] == EndSysex {
break
}
}
command := currentBuffer[1]
switch command {
case CapabilityResponse:
b.pins = []Pin{}
supportedModes := 0
n := 0
for _, val := range currentBuffer[2:(len(currentBuffer) - 5)] {
if val == 127 {
modes := []int{}
for _, mode := range []int{Input, Output, Analog, Pwm, Servo} {
if (supportedModes & (1 << byte(mode))) != 0 {
modes = append(modes, mode)
}
}
b.pins = append(b.pins, Pin{SupportedModes: modes, Mode: Output})
b.AddEvent(fmt.Sprintf("DigitalRead%v", len(b.pins)-1))
b.AddEvent(fmt.Sprintf("PinState%v", len(b.pins)-1))
supportedModes = 0
n = 0
continue
}
if n == 0 {
supportedModes = supportedModes | (1 << val)
}
n ^= 1
}
gobot.Publish(b.Event("CapabilityQuery"), nil)
case AnalogMappingResponse:
pinIndex := 0
b.analogPins = []int{}
for _, val := range currentBuffer[2 : len(b.pins)-1] {
b.pins[pinIndex].AnalogChannel = int(val)
if val != 127 {
b.analogPins = append(b.analogPins, pinIndex)
}
b.AddEvent(fmt.Sprintf("AnalogRead%v", pinIndex))
pinIndex++
}
gobot.Publish(b.Event("AnalogMappingQuery"), nil)
case PinStateResponse:
pin := currentBuffer[2]
b.pins[pin].Mode = int(currentBuffer[3])
b.pins[pin].State = int(currentBuffer[4])
if len(currentBuffer) > 6 {
b.pins[pin].State = int(uint(b.pins[pin].State) | uint(currentBuffer[5])<<7)
}
if len(currentBuffer) > 7 {
b.pins[pin].State = int(uint(b.pins[pin].State) | uint(currentBuffer[6])<<14)
}
gobot.Publish(b.Event(fmt.Sprintf("PinState%v", pin)), b.pins[pin])
case I2CReply:
reply := I2cReply{
Address: int(byte(currentBuffer[2]) | byte(currentBuffer[3])<<7),
Register: int(byte(currentBuffer[4]) | byte(currentBuffer[5])<<7),
Data: []byte{byte(currentBuffer[6]) | byte(currentBuffer[7])<<7},
}
for i := 8; i < len(currentBuffer); i = i + 2 {
if currentBuffer[i] == byte(0xF7) {
break
}
if i+2 > len(currentBuffer) {
break
}
reply.Data = append(reply.Data,
byte(currentBuffer[i])|byte(currentBuffer[i+1])<<7,
)
}
gobot.Publish(b.Event("I2cReply"), reply)
case FirmwareQuery:
name := []byte{}
for _, val := range currentBuffer[4:(len(currentBuffer) - 1)] {
if val != 0 {
name = append(name, val)
}
}
b.FirmwareName = string(name[:])
gobot.Publish(b.Event("FirmwareQuery"), b.FirmwareName)
case StringData:
str := currentBuffer[2:len(currentBuffer)]
gobot.Publish(b.Event("StringData"), string(str[:len(str)-1]))
}
}
return
}