-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCreate2_TetheredDrive.py
296 lines (251 loc) · 10.5 KB
/
Create2_TetheredDrive.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
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# 27 May 2015
# updated 1 April 2020 for Python3
###########################################################################
# Copyright (c) 2015-2020 iRobot Corporation#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
#
# Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in
# the documentation and/or other materials provided with the
# distribution.
#
# Neither the name of iRobot Corporation nor the names
# of its contributors may be used to endorse or promote products
# derived from this software without specific prior written
# permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
###########################################################################
from tkinter import *
import tkinter.messagebox
import tkinter.simpledialog
import struct
import sys, glob # for listing serial ports
try:
import serial
except ImportError:
tkinter.messagebox.showerror('Import error', 'Please install pyserial.')
raise
connection = None
TEXTWIDTH = 40 # window width, in characters
TEXTHEIGHT = 16 # window height, in lines
VELOCITYCHANGE = 50
ROTATIONCHANGE = 50
helpText = """\
Supported Keys:
P\tPassive
S\tSafe
F\tFull
C\tClean
D\tDock
R\tReset
Space\tBeep
Arrows\tMotion
If nothing happens after you connect, try pressing 'P' and then 'S' to get into safe mode.
"""
class TetheredDriveApp(Tk):
# static variables for keyboard callback -- I know, this is icky
callbackKeyUp = False
callbackKeyDown = False
callbackKeyLeft = False
callbackKeyRight = False
callbackKeyLastDriveCommand = ''
def __init__(self):
Tk.__init__(self)
self.title("iRobot Create 2 Tethered Drive")
self.option_add('*tearOff', FALSE)
self.menubar = Menu()
self.configure(menu=self.menubar)
createMenu = Menu(self.menubar, tearoff=False)
self.menubar.add_cascade(label="Create", menu=createMenu)
createMenu.add_command(label="Connect", command=self.onConnect)
createMenu.add_command(label="Help", command=self.onHelp)
createMenu.add_command(label="Quit", command=self.onQuit)
self.text = Text(self, height = TEXTHEIGHT, width = TEXTWIDTH, wrap = WORD)
self.scroll = Scrollbar(self, command=self.text.yview)
self.text.configure(yscrollcommand=self.scroll.set)
self.text.pack(side=LEFT, fill=BOTH, expand=True)
self.scroll.pack(side=RIGHT, fill=Y)
self.text.insert(END, helpText)
self.bind("<Key>", self.callbackKey)
self.bind("<KeyRelease>", self.callbackKey)
# sendCommandASCII takes a string of whitespace-separated, ASCII-encoded base 10 values to send
def sendCommandASCII(self, command):
cmd = bytes([int(v) for v in command.split()])
self.sendCommandRaw(cmd)
# sendCommandRaw takes a string interpreted as a byte array
def sendCommandRaw(self, command):
global connection
try:
if connection is not None:
assert isinstance(command, bytes), 'Command must be of type bytes'
connection.write(command)
connection.flush()
else:
tkinter.messagebox.showerror('Not connected!', 'Not connected to a robot!')
print("Not connected.")
except serial.SerialException:
print("Lost connection")
tkinter.messagebox.showinfo('Uh-oh', "Lost connection to the robot!")
connection = None
seq = ' '.join([ str(c) for c in command ])
self.text.insert(END, ' '.join([ str(c) for c in command ]))
self.text.insert(END, '\n')
self.text.see(END)
# getDecodedBytes returns a n-byte value decoded using a format string.
# Whether it blocks is based on how the connection was set up.
def getDecodedBytes(self, n, fmt):
global connection
try:
return struct.unpack(fmt, connection.read(n))[0]
except serial.SerialException:
print("Lost connection")
tkinter.messagebox.showinfo('Uh-oh', "Lost connection to the robot!")
connection = None
return None
except struct.error:
print("Got unexpected data from serial port.")
return None
# get8Unsigned returns an 8-bit unsigned value.
def get8Unsigned(self):
return getDecodedBytes(1, "B")
# get8Signed returns an 8-bit signed value.
def get8Signed(self):
return getDecodedBytes(1, "b")
# get16Unsigned returns a 16-bit unsigned value.
def get16Unsigned(self):
return getDecodedBytes(2, ">H")
# get16Signed returns a 16-bit signed value.
def get16Signed(self):
return getDecodedBytes(2, ">h")
# A handler for keyboard events. Feel free to add more!
def callbackKey(self, event):
k = event.keysym.upper()
motionChange = False
if event.type == '2': # KeyPress; need to figure out how to get constant
if k == 'P': # Passive
self.sendCommandASCII('128')
elif k == 'S': # Safe
self.sendCommandASCII('131')
elif k == 'F': # Full
self.sendCommandASCII('132')
elif k == 'C': # Clean
self.sendCommandASCII('135')
elif k == 'D': # Dock
self.sendCommandASCII('143')
elif k == 'SPACE': # Beep
self.sendCommandASCII('140 3 1 64 16 141 3')
elif k == 'R': # Reset
self.sendCommandASCII('7')
elif k == 'UP':
self.callbackKeyUp = True
motionChange = True
elif k == 'DOWN':
self.callbackKeyDown = True
motionChange = True
elif k == 'LEFT':
self.callbackKeyLeft = True
motionChange = True
elif k == 'RIGHT':
self.callbackKeyRight = True
motionChange = True
else:
print("not handled", repr(k))
elif event.type == '3': # KeyRelease; need to figure out how to get constant
if k == 'UP':
self.callbackKeyUp = False
motionChange = True
elif k == 'DOWN':
self.callbackKeyDown = False
motionChange = True
elif k == 'LEFT':
self.callbackKeyLeft = False
motionChange = True
elif k == 'RIGHT':
self.callbackKeyRight = False
motionChange = True
if motionChange == True:
velocity = 0
velocity += VELOCITYCHANGE if self.callbackKeyUp is True else 0
velocity -= VELOCITYCHANGE if self.callbackKeyDown is True else 0
rotation = 0
rotation += ROTATIONCHANGE if self.callbackKeyLeft is True else 0
rotation -= ROTATIONCHANGE if self.callbackKeyRight is True else 0
# compute left and right wheel velocities
vr = int(velocity + (rotation/2))
vl = int(velocity - (rotation/2))
# create drive command
cmd = struct.pack(">Bhh", 145, vr, vl)
if cmd != self.callbackKeyLastDriveCommand:
self.sendCommandRaw(cmd)
self.callbackKeyLastDriveCommand = cmd
def onConnect(self):
global connection
if connection is not None:
tkinter.messagebox.showinfo('Oops', "You're already connected!")
return
try:
ports = self.getSerialPorts()
port = tkinter.simpledialog.askstring('Port?', 'Enter COM port to open.\nAvailable options:\n' + '\n'.join(ports))
except EnvironmentError:
port = tkinter.simpledialog.askstring('Port?', 'Enter COM port to open.')
if port is not None:
print("Trying " + str(port) + "... ")
try:
connection = serial.Serial(port, baudrate=115200, timeout=1)
print("Connected!")
tkinter.messagebox.showinfo('Connected', "Connection succeeded!")
except:
print("Failed.")
tkinter.messagebox.showinfo('Failed', "Sorry, couldn't connect to " + str(port))
def onHelp(self):
tkinter.messagebox.showinfo('Help', helpText)
def onQuit(self):
if tkinter.messagebox.askyesno('Really?', 'Are you sure you want to quit?'):
self.destroy()
def getSerialPorts(self):
"""Lists serial ports
From http://stackoverflow.com/questions/12090503/listing-available-com-ports-with-python
:raises EnvironmentError:
On unsupported or unknown platforms
:returns:
A list of available serial ports
"""
if sys.platform.startswith('win'):
ports = ['COM' + str(i + 1) for i in range(256)]
elif sys.platform.startswith('linux') or sys.platform.startswith('cygwin'):
# this is to exclude your current terminal "/dev/tty"
ports = glob.glob('/dev/tty[A-Za-z]*')
elif sys.platform.startswith('darwin'):
ports = glob.glob('/dev/tty.*')
else:
raise EnvironmentError('Unsupported platform')
result = []
for port in ports:
try:
s = serial.Serial(port)
s.close()
result.append(port)
except (OSError, serial.SerialException):
pass
return result
if __name__ == "__main__":
app = TetheredDriveApp()
app.mainloop()