-
Notifications
You must be signed in to change notification settings - Fork 0
/
gokubi.go
375 lines (328 loc) · 9.18 KB
/
gokubi.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
package gobuki
import (
"bufio"
"bytes"
"encoding/gob"
"fmt"
"io"
"net"
"sync"
"time"
"github.com/jacobsa/go-serial/serial"
"github.com/tinogoehlert/gobuki/commands"
"github.com/tinogoehlert/gobuki/packets"
"github.com/tinogoehlert/gobuki/sensors"
)
// FeedbackData represents a collection of Feedback Data
type FeedbackData struct {
BasicSensor *sensors.BasicSensor
DockingIR *sensors.DockingIR
InerTial *sensors.Inertial
CliffADC *sensors.CliffADC
CurrenWheels *sensors.CurrentWheels
}
// Callback represents a Callback that carries changed data from kobuki bot
type Callback func(interface{})
// AllCallback represents a Callback that carries changed data from kobuki bot
type AllCallback func(string, interface{})
// ToleranceCfg represents the tolerance settings for specific sensors
type ToleranceCfg struct {
gyro float64
cliffADC int
currentWheels int
}
// Module represents a Kobuki Bot Module
type Module interface {
Tick(FeedbackData) *commands.Command
}
// Bot Represents a Kobuki Bot
type Bot struct {
conn io.ReadWriteCloser
lastFrame FeedbackData
currentFrame FeedbackData
Gyro *sensors.Gyro
ControllerGain *sensors.ControllerGain
callBacks map[string][]Callback
allCallback []AllCallback
cmdChan chan commands.Command
logChan chan string
modules []Module
toleranceCfg ToleranceCfg
hardwareVersion Version
firmwareVersion Version
uid UniqueID
mutex sync.Mutex
}
func init() {
gob.Register(sensors.Bumper{})
gob.Register(sensors.Buttons{})
gob.Register(sensors.GyroData{})
gob.Register(sensors.WheelsDrop{})
gob.Register(sensors.WheelsEncoder{})
gob.Register(sensors.WheelsPWM{})
gob.Register(sensors.Inertial{})
gob.Register(sensors.DockingIR{})
gob.Register(sensors.Cliff{})
gob.Register(sensors.CliffADC{})
gob.Register(sensors.Discharging)
}
// NewBotTCP creates a new Bot instance and connects to a Kobuki Bot
func NewBotTCP(address string) (*Bot, error) {
client, err := net.DialTimeout("tcp", address, 5*time.Second)
if err != nil {
return nil, fmt.Errorf("could not dial targetHost: %s", err.Error())
}
client.(*net.TCPConn).SetLinger(2)
client.(*net.TCPConn).SetKeepAlive(true)
client.(*net.TCPConn).SetReadBuffer(1)
bot := Bot{conn: client}
bot.initBot()
return &bot, nil
}
// NewBotSerial creates a new Bot instance and connects to a Kobuki Bot via serial port
func NewBotSerial(dev string) (*Bot, error) {
// Open the port.
port, err := serial.Open(serial.OpenOptions{
PortName: dev,
BaudRate: 115200,
DataBits: 8,
StopBits: 1,
ParityMode: serial.PARITY_NONE,
MinimumReadSize: 4,
})
if err != nil {
return nil, fmt.Errorf("could not open serial: %s", err.Error())
}
bot := Bot{conn: port}
bot.initBot()
return &bot, nil
}
func (k *Bot) initBot() {
k.Gyro = sensors.NewGyroADC(64, 8)
k.ControllerGain = &sensors.ControllerGain{}
k.cmdChan = make(chan commands.Command, 1)
k.callBacks = make(map[string][]Callback)
k.logChan = make(chan string)
k.allCallback = []AllCallback{}
k.modules = []Module{}
k.toleranceCfg = ToleranceCfg{
gyro: 0.01,
cliffADC: 50,
}
}
// Stop disconnects from a Bot
func (k *Bot) Stop() {
k.conn.Close()
}
// Start read loop
func (k *Bot) Start() {
packetReader := packets.NewPacketReader(bufio.NewReader(k.conn))
go func() {
versionCmd := commands.RequestCmd()
k.conn.Write(versionCmd.Serialize())
for {
select {
case cmd := <-k.cmdChan:
_, err := k.conn.Write(cmd.Serialize())
if err != nil {
fmt.Printf("could not send command: %s\n", err.Error())
}
default:
}
b, err := packetReader.ReadData()
if err != nil {
k.logChan <- err.Error()
}
if b != nil {
currentFrame := k.parseFrame(b)
k.hasChangedData(currentFrame)
k.lastFrame = currentFrame
for _, m := range k.modules {
cmd := m.Tick(currentFrame)
if cmd != nil {
k.conn.Write(cmd.Serialize())
}
}
}
}
}()
return
}
// HardwareVersion returns HardwareVersion string
func (k *Bot) HardwareVersion() string {
return k.hardwareVersion.String()
}
// FirmwareVersion returns FirmwareVersion string
func (k *Bot) FirmwareVersion() string {
return k.firmwareVersion.String()
}
// UniqueID returns UID string
func (k *Bot) UniqueID() string {
return k.uid.String()
}
// SetCliffADCTolerance set tolerance for Cliff ADC
func (k *Bot) SetCliffADCTolerance(t int) {
k.toleranceCfg.cliffADC = t
}
// SetGyroTolerance set tolerance for gyroscope
func (k *Bot) SetGyroTolerance(t float64) {
k.toleranceCfg.gyro = t
}
// SetCurrentWheelsTolerance set tolerance for wheels current
func (k *Bot) SetCurrentWheelsTolerance(t int) {
k.toleranceCfg.currentWheels = t
}
//On registers a new Callback
func (k *Bot) On(event string, cb Callback) {
k.mutex.Lock()
if _, ok := k.callBacks[event]; !ok {
k.callBacks[event] = []Callback{}
}
k.callBacks[event] = append(k.callBacks[event], cb)
k.mutex.Unlock()
}
//OnAll registers a new Callback for all events
func (k *Bot) OnAll(cb AllCallback) {
k.mutex.Lock()
k.allCallback = append(k.allCallback, cb)
k.mutex.Unlock()
}
// Send sends Command to Bot
func (k *Bot) Send(cmd commands.Command) {
k.cmdChan <- cmd
}
// LogChannel waits and returns log entry. blocking
func (k *Bot) LogChannel() string {
return <-k.logChan
}
// AddModule adds a module
func (k *Bot) AddModule(m Module) {
k.mutex.Lock()
k.modules = append(k.modules, m)
k.mutex.Unlock()
}
func (k *Bot) emitEvent(name string, data interface{}) {
if callbacks, ok := k.callBacks[name]; ok {
for _, callback := range callbacks {
callback(data)
}
}
for _, callback := range k.allCallback {
callback(name, data)
}
}
func (k *Bot) hasChangedData(current FeedbackData) {
if current.BasicSensor != nil && k.lastFrame.BasicSensor != nil {
if !current.BasicSensor.Wheels.Drop.Equals(
&k.lastFrame.BasicSensor.Wheels.Drop,
) {
k.emitEvent("WheelsDrop", ¤t.BasicSensor.Wheels.Drop)
}
if !current.BasicSensor.Wheels.Encoder.Equals(
&k.lastFrame.BasicSensor.Wheels.Encoder,
) {
k.emitEvent("WheelsEncoder", ¤t.BasicSensor.Wheels.Encoder)
}
if !current.BasicSensor.Wheels.PWM.Equals(
&k.lastFrame.BasicSensor.Wheels.PWM,
) {
k.emitEvent("WheelsPWM", ¤t.BasicSensor.Wheels.PWM)
}
if !current.BasicSensor.Cliff.Equals(&k.lastFrame.BasicSensor.Cliff) {
k.emitEvent("Cliff", ¤t.BasicSensor.Cliff)
}
if !current.BasicSensor.Bumper.Equals(&k.lastFrame.BasicSensor.Bumper) {
k.emitEvent("Bumper", ¤t.BasicSensor.Bumper)
}
if !current.BasicSensor.Buttons.Equals(&k.lastFrame.BasicSensor.Buttons) {
k.emitEvent("Buttons", ¤t.BasicSensor.Buttons)
}
if current.BasicSensor.ChargeState != k.lastFrame.BasicSensor.ChargeState {
k.emitEvent("ChargeState", ¤t.BasicSensor.ChargeState)
}
if current.BasicSensor.BatteryVoltage != k.lastFrame.BasicSensor.BatteryVoltage {
k.emitEvent("BatteryVoltage", ¤t.BasicSensor.BatteryVoltage)
}
}
if current.DockingIR != nil {
if !current.DockingIR.Equals(k.lastFrame.DockingIR) {
k.emitEvent("DockingIR", current.DockingIR)
}
}
if current.CliffADC != nil {
if !current.CliffADC.Equals(k.lastFrame.CliffADC, k.toleranceCfg.cliffADC) {
k.emitEvent("CliffADC", current.CliffADC)
}
}
if current.CurrenWheels != nil {
if !current.CurrenWheels.Equals(k.lastFrame.CurrenWheels, k.toleranceCfg.currentWheels) {
k.emitEvent("CurrentWheels", current.CurrenWheels)
}
}
if k.Gyro != nil && k.Gyro.Changed(k.toleranceCfg.gyro) {
k.emitEvent("Gyro", k.Gyro.GetNewData())
}
if current.InerTial != nil {
if !current.InerTial.Equals(k.lastFrame.InerTial) {
k.emitEvent("Inertial", current.InerTial)
}
}
}
func (k *Bot) parseFrame(buffer []byte) FeedbackData {
var data FeedbackData
for offset := 0; (offset + 1) < len(buffer); {
var (
subID = int(buffer[offset])
subLen = int(buffer[offset+1])
payload = buffer[offset+2 : offset+subLen+2]
err error
)
switch subID {
case 0x01:
data.BasicSensor, err = sensors.NewBasicSensorFromBytes(payload)
case 0x03:
data.DockingIR, err = sensors.NewDockingIRFromBytes(payload)
case 0x04:
data.InerTial, err = sensors.NewInertialFromBytes(payload)
case 0x05:
data.CliffADC, err = sensors.NewCliffADCFromBytes(payload)
case 0x06:
data.CurrenWheels, err = sensors.NewCurrentWheelsFromBytes(payload)
case 0x0A:
err = k.hardwareVersion.FromBytes(payload)
case 0x0B:
err = k.firmwareVersion.FromBytes(payload)
case 0x0D:
err = k.Gyro.FromBytes(payload)
case 0x0F:
// TODO
break
case 0x10:
// TODO
break
case 0x13:
err = k.uid.FromBytes(payload)
case 0x15:
err = k.ControllerGain.FromBytes(payload)
}
if err != nil {
k.logChan <- fmt.Sprintf("[%d] could not parse data: %s", subID, err.Error())
}
offset += subLen + 2
}
return data
}
// EncodeGob encode data to goba
func EncodeGob(data interface{}) ([]byte, error) {
b := new(bytes.Buffer)
err := gob.NewEncoder(b).Encode(data)
if err != nil {
return nil, err
}
return b.Bytes(), nil
}
// DecodeGob data to gob
func DecodeGob(data []byte, v interface{}) error {
b := bytes.NewBuffer(data)
return gob.NewDecoder(b).Decode(v)
}