-
Notifications
You must be signed in to change notification settings - Fork 1
/
pyrobot.py
511 lines (418 loc) · 16.3 KB
/
pyrobot.py
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
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
#!/usr/bin/python
# The MIT License
#
# Copyright (c) 2007 Damon Kohler
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
"""iRobot Roomba Serial Control Interface (SCI) and Create Open Interface (OI).
PyRobot was originally based on openinterface.py, developed by iRobot
Corporation. Many of the docstrings from openinterface.py, particularly those
which describe the specification, are also used here. Also, docstrings may
contain specification text copied directly from the Roomba SCI Spec Manual and
the Create Open Interface specification.
Since SCI is a subset of OI, PyRobot first defines the Roomba's functionality
in the Roomba class and then extends that with the Create's additional
functionality in the Create class. In addition, since OI is built on SCI the
SerialCommandInterface class is also used for OI.
"""
__author__ = "damonkohler@gmail.com (Damon Kohler)"
import serial
import struct
import time
import threading
import math
ROOMBA_OPCODES = dict(
start = 128,
baud = 129,
control = 130,
safe = 131,
full = 132,
power = 133,
spot = 134,
clean = 135,
max = 136,
drive = 137,
motors = 138,
leds = 139,
song = 140,
play = 141,
sensors = 142,
force_seeking_dock = 143,
)
CREATE_OPCODES = dict(
pwm_low_side_drivers = 144,
direct_drive = 145,
digital_outputs = 147,
stream = 148,
query_list = 149,
pause_resume_stream = 150,
send_ir = 151,
script = 152,
play_script = 153,
show_script = 154,
wait_time = 155,
wait_distance = 156,
wait_angle = 157,
wait_event = 158,
)
IR_OPCODES = dict(
# Remote control.
left = 129,
forward = 130,
right = 131,
spot = 132,
max = 133,
small = 134,
medium = 135,
large = 136,
clean = 136,
pause = 137,
power = 138,
arc_left = 139,
arc_right = 140,
drive_stop = 141,
# Scheduling remote.
send_all = 142,
seek_dock = 143,
# Home base.
reserved = 240,
force_field = 242,
green_buoy = 244,
red_buoy = 248,
red_buoy_and_force = 250,
red_and_green_buoy = 252,
red_green_and_force = 254,
)
BAUD_RATES = ( # In bits per second.
300,
600,
1200,
2400,
4800,
9600,
14400,
19200,
28800,
38400,
57600, # Default.
115200)
CHARGING_STATES = (
'not-charging',
'charging-recovery',
'charging',
'trickle-charging',
'waiting',
'charging-error')
# From: http://www.harmony-central.com/MIDI/Doc/table2.html
MIDI_TABLE = {'rest': 0, 'R': 0, 'pause': 0,
'G1': 31, 'G#1': 32, 'A1': 33,
'A#1': 34, 'B1': 35,
'C2': 36, 'C#2': 37, 'D2': 38,
'D#2': 39, 'E2': 40, 'F2': 41,
'F#2': 42, 'G2': 43, 'G#2': 44,
'A2': 45, 'A#2': 46, 'B2': 47,
'C3': 48, 'C#3': 49, 'D3': 50,
'D#3': 51, 'E3': 52, 'F3': 53,
'F#3': 54, 'G3': 55, 'G#3': 56,
'A3': 57, 'A#3': 58, 'B3': 59,
'C4': 60, 'C#4': 61, 'D4': 62,
'D#4': 63, 'E4': 64, 'F4': 65,
'F#4': 66, 'G4': 67, 'G#4': 68,
'A4': 69, 'A#4': 70, 'B4': 71,
'C5': 72, 'C#5': 73, 'D5': 74,
'D#5': 75, 'E5': 76, 'F5': 77,
'F#5': 78, 'G5': 79, 'G#5': 80,
'A5': 81, 'A#5': 82, 'B5': 83,
'C6': 84, 'C#6': 85, 'D6': 86,
'D#6': 87, 'E6': 88, 'F6': 89,
'F#6': 90, 'G6': 91, 'G#6': 92,
'A6': 93, 'A#6': 94, 'B6': 95,
'C7': 96, 'C#7': 97, 'D7': 98,
'D#7': 99, 'E7': 100, 'F7': 101,
'F#7': 102, 'G7': 103, 'G#7': 104,
'A7': 105, 'A#7': 106, 'B7': 107,
'C8': 108, 'C#8': 109, 'D8': 110,
'D#8': 111, 'E8': 112, 'F8': 113,
'F#8': 114, 'G8': 115, 'G#8': 116,
'A8': 117, 'A#8': 118, 'B8': 119,
'C9': 120, 'C#9': 121, 'D9': 122,
'D#9': 123, 'E9': 124, 'F9': 125,
'F#9': 126, 'G9': 127}
# Drive constants.
RADIUS_TURN_IN_PLACE_CW = -1
RADIUS_TURN_IN_PLACE_CCW = 1
RADIUS_STRAIGHT = 32768
RADIUS_MAX = 2000
VELOCITY_MAX = 500 # mm/s
VELOCITY_SLOW = VELOCITY_MAX * 0.33
VELOCITY_FAST = VELOCITY_MAX * 0.66
WHEEL_SEPARATION = 298 # mm
assert struct.calcsize('H') == 2, 'Expecting 2-byte shorts.'
class PyRobotError(Exception):
pass
class SerialCommandInterface(object):
"""A higher-level wrapper around PySerial specifically designed for use with
iRobot's SCI.
"""
def __init__(self, tty, baudrate):
self.ser = serial.Serial(tty, baudrate=baudrate)
self.ser.open()
self.opcodes = {}
self.lock = threading.RLock()
# TODO(damonkohler): Set up locking for polling and reading sensor data in
# a separate thread.
def __del__(self):
self.ser.close()
def Wake(self):
"""Wake up robot."""
self.ser.setRTS(0)
time.sleep(0.1)
self.ser.setRTS(1)
time.sleep(1) # Technically it should wake after 500ms.
def AddOpcodes(self, opcodes):
"""Add available opcodes to the SCI."""
self.opcodes.update(opcodes)
def Send(self, bytes):
"""Send a string of bytes to the robot."""
self.ser.write(struct.pack('B' * len(bytes), *bytes))
def Read(self, num_bytes):
"""Read a string of 'num_bytes' bytes from the robot."""
#return struct.unpack('B' * num_bytes, self.ser.read(num_bytes))
return self.ser.read(num_bytes)
def __getattr__(self, name):
"""Creates methods for opcodes on the fly.
Each opcode method sends the opcode optionally followed by a string of
bytes.
"""
if name in self.opcodes:
def SendOpcode(*bytes):
self.Send([self.opcodes[name]] + list(bytes))
return SendOpcode
raise AttributeError
class RoombaSensors(object):
"""Retrive and decode the Roomba's sensor data.
Some of the specification is included in the docstrings. For a complete
description, see the Roomba SCI Sepc Manual.
"""
def __init__(self, roomba):
self.roomba = roomba
self.sensors = {}
def Poll(self):
"""Keep sensor data up to date by polling for it periodically.
According to the OI spec, sensor data is updated every 15 ms and should not
be polled more often than that. There is no such specification in the SCI
spec.
"""
pass
def GetAll(self):
"""Request and decode all available sensor data."""
self.roomba.sci.sensors(0)
bytes = self.roomba.sci.Read(26)
bytes = list(bytes)
# NOTE(damonkohler): We decode sensor data in reverse order for better pop
# performance.
self.DecodeUnsignedShort('capacity', bytes.pop(), bytes.pop()) # mAh
self.DecodeUnsignedShort('charge', bytes.pop(), bytes.pop()) # mAh
self.DecodeByte('temperature', bytes.pop()) # C
self.DecodeShort('current', bytes.pop(), bytes.pop()) # mA
self.DecodeUnsignedShort('voltage', bytes.pop(), bytes.pop()) # mV
self.DecodeUnsignedByte('charging-state', bytes.pop())
self.Angle(bytes.pop(), bytes.pop(), 'degrees')
self.DecodeShort('distance', bytes.pop(), bytes.pop()) # mm
self.Buttons(bytes.pop())
self.DecodeUnsignedByte('remote-opcode', bytes.pop())
self.DecodeUnsignedByte('dirt-detector-right', bytes.pop())
self.DecodeUnsignedByte('dirt-detector-left', bytes.pop())
self.MotorOvercurrents(bytes.pop())
self.DecodeBool('virtual-wall', bytes.pop())
self.DecodeBool('cliff-right', bytes.pop())
self.DecodeBool('cliff-front-right', bytes.pop())
self.DecodeBool('cliff-front-left', bytes.pop())
self.DecodeBool('cliff-left', bytes.pop())
self.DecodeBool('wall', bytes.pop())
self.BumpsWheeldrops(bytes.pop())
def Angle(self, low, high, unit=None):
"""The angle that Roomba has turned through since the angle was last
requested. The angle is expressed as the difference in the distance
traveled by Roomba's two wheels in millimeters, specifically the right
wheel distance minus the left wheel distance, divided by two. This makes
counter-clockwise angles positive and clockwise angles negative. This can
be used to directly calculate the angle that Roomba has turned through
since the last request. Since the distance between Roomba's wheels is
258mm, the equations for calculating the angles in familiar units are:
Angle in radians = (2 * difference) / 258
Angle in degrees = (360 * difference) / (258 * Pi).
If the value is not polled frequently enough, it will be capped at its
minimum or maximum.
Note: Reported angle and distance may not be accurate. Roomba measures
these by detecting its wheel revolutions. If for example, the wheels slip
on the floor, the reported angle of distance will be greater than the
actual angle or distance.
"""
if unit not in (None, 'radians', 'degrees'):
raise PyRobotError('Invalid angle unit specified.')
self.DecodeShort('angle', low, high)
if unit == 'radians':
self.sensors['angle'] = (2 * self.sensors['angle']) / 258
if unit == 'degrees':
self.sensors['angle'] /= math.pi
def BumpsWheeldrops(self, byte):
"""The state of the bump (0 = no bump, 1 = bump) and wheeldrop sensors
(0 = wheel up, 1 = wheel dropped) are sent as individual bits.
Note: Some robots do not report the three wheel drops separately. Instead,
if any of the three wheels drops, all three wheel-drop bits will be set.
You can tell which kind of robot you have by examining the serial number
inside the battery compartment. Wheel drops are separate only if there
is an 'E' in the serial number.
"""
byte = struct.unpack('B', byte)[0]
self.sensors.update({
'wheel-drop-caster': bool(byte & 0x10),
'wheel-drop-left': bool(byte & 0x08),
'wheel-drop-right': bool(byte & 0x04),
'bump-left': bool(byte & 0x02),
'bump-right': bool(byte & 0x01)})
def MotorOvercurrents(self, byte):
"""The state of the five motors overcurrent sensors are sent as individual
bits (0 = no overcurrent, 1 = overcurrent).
"""
byte = struct.unpack('B', byte)[0]
self.sensors.update({
'drive-left': bool(byte & 0x10),
'drive-right': bool(byte & 0x08),
'main-brush': bool(byte & 0x04),
'vacuum': bool(byte & 0x02),
'side-brush': bool(byte & 0x01)})
def Buttons(self, byte):
"""The state of the four Roomba buttons are sent as individual bits
(0 = button not pressed, 1 = button pressed).
"""
byte = struct.unpack('B', byte)[0]
self.sensors.update({
'power': bool(byte & 0x08),
'spot': bool(byte & 0x04),
'clean': bool(byte & 0x02),
'max': bool(byte & 0x01)})
def DecodeBool(self, name, byte):
"""Decode 'byte' as a bool and map it to 'name'."""
self.sensors[name] = bool(byte)
# NOTE(damonkohler): We specify the low byte first to make it easier when
# popping bytes off a list.
def DecodeUnsignedShort(self, name, low, high):
"""Map an unsigned short from a 'high' and 'low' bytes to 'name'."""
self.sensors[name] = struct.unpack('>H', high + low)[0]
def DecodeShort(self, name, low, high):
"""Map a short from a 'high' and 'low' bytes to 'name'."""
self.sensors[name] = struct.unpack('>h', high + low)[0]
def DecodeByte(self, name, byte):
"""Map signed 'byte' to 'name'."""
self.sensors[name] = struct.unpack('b', byte)[0]
def DecodeUnsignedByte(self, name, byte):
"""Map unsigned 'byte' to 'name'."""
self.sensors[name] = struct.unpack('B', byte)[0]
class Roomba(object):
"""Represents a Roomba robot."""
def __init__(self, tty='/dev/ttyUSB0'):
self.tty = tty
self.sci = SerialCommandInterface(tty, 57600)
self.sci.AddOpcodes(ROOMBA_OPCODES)
def ChangeBaudRate(self, baud_rate):
"""Sets the baud rate in bits per second (bps) at which SCI commands and
data are sent according to the baud code sent in the data byte.
The default baud rate at power up is 57600 bps. (See Serial Port Settings,
above.) Once the baud rate is changed, it will persist until Roomba is
power cycled by removing the battery (or until the battery voltage falls
below the minimum required for processor operation). You must wait 100ms
after sending this command before sending additional commands at the new
baud rate. The SCI must be in passive, safe, or full mode to accept this
command. This command puts the SCI in passive mode.
"""
if baud_rate not in BAUD_RATES:
raise PyRobotError('Invalid baud rate specified.')
self.sci.baud(baud_rate)
self.sci = SerialCommandInterface(self.tty, baud_rate)
def Control(self):
"""Start the robot's SCI interface and place it in safe mode."""
self.sci.start()
self.sci.control()
def Drive(self, velocity, radius):
"""Controls Roomba's drive wheels.
NOTE(damonkohler): The following specification applies to both the Roomba
and the Create.
The Roomba takes four data bytes, interpreted as two 16-bit signed values
using two's complement. The first two bytes specify the average velocity
of the drive wheels in millimeters per second (mm/s), with the high byte
being sent first. The next two bytes specify the radius in millimeters at
which Roomba will turn. The longer radii make Roomba drive straighter,
while the shorter radii make Roomba turn more. The radius is measured from
the center of the turning circle to the center of Roomba.
A Drive command with a positive velocity and a positive radius makes
Roomba drive forward while turning toward the left. A negative radius
makes Roomba turn toward the right. Special cases for the radius make
Roomba turn in place or drive straight, as specified below. A negative
velocity makes Roomba drive backward.
Also see DriveStraight and TurnInPlace convenience methods.
"""
# Mask integers to 2 bytes.
velocity = int(velocity) & 0xffff
radius = int(radius) & 0xffff
# Pack as shorts to get 2 x 2 byte integers. Unpack as 4 bytes to send.
# TODO(damonkohler): The 4 unpacked bytes will just be repacked later,
# that seems dumb to me.
bytes = struct.unpack('4B', struct.pack('>2H', velocity, radius))
self.sci.drive(*bytes)
def Stop(self):
"""Set velocity and radius to 0 to stop movement."""
self.Drive(0, 0)
def SlowStop(self, velocity):
"""Slowly reduce the velocity to 0 to stop movement."""
velocities = xrange(velocity, VELOCITY_SLOW, -25)
if velocity < 0:
velocities = xrange(velocity, -VELOCITY_SLOW, 25)
for v in velocities:
self.Drive(v, RADIUS_STRAIGHT)
time.sleep(0.25)
self.Stop()
def DriveStraight(self, velocity):
"""Drive in a straight line."""
self.Drive(velocity, RADIUS_STRAIGHT)
def TurnInPlace(self, velocity, direction):
"""Turn in place either clockwise or counter-clockwise."""
valid_directions = {'cw': RADIUS_TURN_IN_PLACE_CW,
'ccw': RADIUS_TURN_IN_PLACE_CCW}
self.Drive(velocity, valid_directions[direction])
class CreateSensors(RoombaSensors):
"""Handles retrieving and decoding the Create's sensor data."""
pass
class Create(Roomba):
"""Represents a Create robot."""
pass
if __name__ == '__main__':
"""Do a little dance."""
r = Roomba()
r.sci.Wake()
r.Control()
time.sleep(0.25)
r.TurnInPlace(VELOCITY_FAST, 'cw')
time.sleep(0.25)
r.TurnInPlace(VELOCITY_FAST, 'ccw')
time.sleep(0.25)
r.DriveStraight(VELOCITY_FAST)
time.sleep(0.25)
r.Stop()