root / scout / scoutsim / GUI.py @ 071926c2
History | View | Annotate | Download (17.3 KB)
1 |
#!/usr/bin/python
|
---|---|
2 |
|
3 |
# Behavior GUI
|
4 |
|
5 |
# shell subprocess libs
|
6 |
import subprocess |
7 |
import shlex #for converting string commands to tokens |
8 |
import sys |
9 |
|
10 |
# GUI libs
|
11 |
import wx |
12 |
import wx.lib.intctrl |
13 |
import wx.lib.agw.floatspin |
14 |
|
15 |
# not sure why these 2 are here
|
16 |
import string |
17 |
import signal |
18 |
|
19 |
# ros imports for spawning and killing scout
|
20 |
import rospy |
21 |
import roslib |
22 |
import os |
23 |
roslib.load_manifest("scoutsim")
|
24 |
|
25 |
# scoutsim imports
|
26 |
from scoutsim.srv import * |
27 |
|
28 |
from collections import defaultdict |
29 |
|
30 |
|
31 |
class Behaviors(object): |
32 |
def __init__(self): |
33 |
self.behaviors = []
|
34 |
self.loadBehaviorList()
|
35 |
# this takes advantage of the fact that our behavior list start at 1
|
36 |
#behaviors = ["Pause", "CW Circle", "CCW Circle", "Odometry",
|
37 |
# "Navigation Map", "Scheduler", "Warehouse",
|
38 |
# "Line Follow", "WL Test", "Maze Solve"]
|
39 |
# @classmethod
|
40 |
# def getListFromDir(self):
|
41 |
# behaviors = []
|
42 |
# for path, dirname, fnames in sorted(os.walk('../libscout/src')):
|
43 |
# if 'src/behaviors' in path or 'src/test_behaviors' in path:
|
44 |
# print "The path is!!!!!!!!!!!!", path
|
45 |
# path_parts = path.split('/')
|
46 |
#
|
47 |
# for f in sorted(fnames):
|
48 |
# # The pause_scout behavior needs to go first!
|
49 |
# print f
|
50 |
# if f.endswith('.h') and 'pause_scout' in f:
|
51 |
# behaviors.insert(0, f.split('.')[0])
|
52 |
# # Everything else goes in alphabetical order
|
53 |
# elif f.endswith('.h'):
|
54 |
# behaviors.append(f.split('.')[0])
|
55 |
# return behaviors
|
56 |
|
57 |
|
58 |
def loadBehaviorList(self): |
59 |
filename = "behaviorList.txt"
|
60 |
print "laoding behavior list!!!" |
61 |
with open(filename, "r") as f: |
62 |
for line in f.read().rstrip().split("\n"): |
63 |
self.behaviors+= [line]
|
64 |
|
65 |
def getNumber(self, behaviorName): |
66 |
if (behaviorName in self.behaviors): |
67 |
return self.behaviors.index(behaviorName) |
68 |
|
69 |
def getName(self, index): |
70 |
if (0 <= index < len(self.Behavior)): |
71 |
return self.behaviors[index] |
72 |
else:
|
73 |
return -1 |
74 |
|
75 |
def getBehaviors(self): |
76 |
# "Pause" is not considered a behavior in GUI
|
77 |
return self.behaviors[1:] |
78 |
|
79 |
# each scout is represented by this class
|
80 |
class Scout(object): |
81 |
numOfScouts = 0 # class variable keeping track of scouts |
82 |
|
83 |
def __init__(self, x=0, y=0, theta=0, name=u"", behaviors=None, |
84 |
Scouts=None, oninit = False): |
85 |
Scout.numOfScouts += 1 # reverted if not successful |
86 |
if len(name) == 0: |
87 |
# automatically give name according to numOfScouts
|
88 |
name = self.autoNameGen(Scouts)
|
89 |
# set vars
|
90 |
self.name = name
|
91 |
self.behavior = "chilling" |
92 |
self.process = None# used to keep track of all processes |
93 |
# related to this scout
|
94 |
self.paused = False |
95 |
self.valid = False |
96 |
# these vars are right now just the original position
|
97 |
# but when ODOMETRY is done, we could actually use them
|
98 |
self.x, self.y = x, y |
99 |
self.theta = theta
|
100 |
|
101 |
self.behaviors = behaviors
|
102 |
|
103 |
# spawn the scout if it is not scout1 (automatically spawned)
|
104 |
if (not oninit): |
105 |
if (self.SpawnInSimulator()): |
106 |
# spawned correctly
|
107 |
self.valid = True |
108 |
else:
|
109 |
Scout.numOfScouts -= 1;
|
110 |
|
111 |
|
112 |
def autoNameGen(self, Scouts): |
113 |
i = 1
|
114 |
while (True): |
115 |
if not (("scout%d"%i) in Scouts): |
116 |
return "scout%d"%i |
117 |
i+=1
|
118 |
|
119 |
|
120 |
# update the classvariable
|
121 |
|
122 |
|
123 |
def SpawnInSimulator(self): |
124 |
try:
|
125 |
# ros spawn routine
|
126 |
rospy.wait_for_service('/spawn');
|
127 |
service = rospy.ServiceProxy('/spawn', Spawn);
|
128 |
response = service(self.x, self.y, self.theta, self.name) |
129 |
return True |
130 |
except rospy.ServiceException as Error: |
131 |
return False |
132 |
|
133 |
def terminateOldBehavior(self): |
134 |
if self.process != None: |
135 |
# now terminate the process
|
136 |
self.process.terminate() #TODO: this kills the process |
137 |
# but maybe not the rosnode
|
138 |
# change to "rosnode kill" instead
|
139 |
# make sure old behavior is terminated before we run the new one
|
140 |
self.process.wait()
|
141 |
|
142 |
# the following lines causes lag and does not solve real issues
|
143 |
# first unregister the node
|
144 |
cmd = "rosnode kill /%sBehavior"%self.name |
145 |
temp = subprocess.Popen(cmd, shell=True)
|
146 |
temp.wait() |
147 |
# this node loses contact but still is not cleaned up in rosnode
|
148 |
# however, this should not affect usage at all.
|
149 |
|
150 |
def changeBehavior(self, behavior): |
151 |
self.behavior = behavior
|
152 |
if (behavior == "pause"): |
153 |
self.paused = True |
154 |
else:
|
155 |
self.paused = False |
156 |
self.terminateOldBehavior()
|
157 |
# do rosprocess calls for new behavior
|
158 |
roscommand = ("rosrun libscout libscout %s %s"%
|
159 |
(self.behaviors.getNumber(self.behavior), self.name)) |
160 |
self.process = subprocess.Popen(roscommand, shell=True) |
161 |
|
162 |
def teleop(self): |
163 |
# teleop involved only one command \
|
164 |
self.terminateOldBehavior()
|
165 |
self.process = None |
166 |
cmd = "rosservice call /set_teleop %s"%self.name |
167 |
try:
|
168 |
subprocess.Popen(shlex.split(cmd), shell=False)
|
169 |
except:
|
170 |
#not sure why this is happening....
|
171 |
# seems to be a ros thing
|
172 |
print "warning, socket error, ignored" |
173 |
|
174 |
def sonar_viz(self, on_off): |
175 |
# teleop involved only one command \
|
176 |
cmd = "rosservice call /set_sonar_viz %s %s"%(on_off, self.name) |
177 |
try:
|
178 |
subprocess.Popen(shlex.split(cmd), shell=False)
|
179 |
except:
|
180 |
#not sure why this is happening....
|
181 |
# seems to be a ros thing
|
182 |
print "warning, socket error, ignored" |
183 |
|
184 |
def killSelf(self): |
185 |
# terminate its current behavior
|
186 |
self.terminateOldBehavior()
|
187 |
|
188 |
# ros call to kill scout in simulator
|
189 |
try:
|
190 |
rospy.wait_for_service("/kill")
|
191 |
service = rospy.ServiceProxy("/kill", Kill)
|
192 |
response = service(self.name)
|
193 |
Scout.numOfScouts -= 1
|
194 |
self.valid = False |
195 |
except rospy.ServiceException, e:
|
196 |
print "warning: kill scout unsuccessful" |
197 |
self.valid = True |
198 |
# remove from the class
|
199 |
|
200 |
|
201 |
# a wrapper for wx Frame
|
202 |
class Window(wx.App): |
203 |
def __init__(self, title=""): |
204 |
super(Window, self).__init__() |
205 |
self.initUIFrame()
|
206 |
|
207 |
def initUIFrame(self): |
208 |
self.GUIFrame = GUI(None, "hallo!") |
209 |
|
210 |
|
211 |
# actual GUI frame
|
212 |
class GUI(wx.Frame): |
213 |
def __init__(self, parent, title): |
214 |
super(GUI, self).__init__(parent, title=title, |
215 |
style=wx.DEFAULT_FRAME_STYLE ^ wx.RESIZE_BORDER, size=(600, 600)) |
216 |
|
217 |
# open up scoutsim race
|
218 |
if len(sys.argv) > 1: |
219 |
map_name = sys.argv[1]
|
220 |
else:
|
221 |
map_name = "race"
|
222 |
command = shlex.split("rosrun scoutsim scoutsim_node " + map_name)
|
223 |
self.simWindowProcess = subprocess.Popen(command, shell=False) |
224 |
#rospy.wait_for_service('/spawn') #don't know why this is here
|
225 |
|
226 |
# register call back for on close cleanup
|
227 |
self.Bind(wx.EVT_CLOSE, self.onClose) |
228 |
|
229 |
|
230 |
self.initData()
|
231 |
self.initUI()
|
232 |
self.Show(True) |
233 |
|
234 |
# do clean up after user close the window
|
235 |
def onClose(self, event): |
236 |
print "Cleaning up all Processes" |
237 |
|
238 |
# kill all the behavior processes
|
239 |
for scout in self.scouts: |
240 |
process = self.scouts[scout].process
|
241 |
if (process != None): |
242 |
process.terminate() |
243 |
|
244 |
# kill the scout sim window
|
245 |
self.simWindowProcess.terminate()
|
246 |
print "done" |
247 |
self.Destroy()
|
248 |
|
249 |
def initData(self): |
250 |
self.scouts = {}
|
251 |
#FIXME: these arguments are not right...fix them!!!
|
252 |
self.behaviors = Behaviors()
|
253 |
self.scouts["scout1"] = Scout(x=0, y=0, theta=0, name="scout1", |
254 |
behaviors=self.behaviors,
|
255 |
Scouts = self.scouts, oninit=True) |
256 |
|
257 |
# addButton callback
|
258 |
def addScout(self, x_wx, y_wx, theta_wx, name_wx): |
259 |
# x, y, theta, name are given as wx Inputs
|
260 |
x = x_wx.GetValue() |
261 |
y = y_wx.GetValue() |
262 |
theta = theta_wx.GetValue() |
263 |
name = name_wx.GetValue() |
264 |
newSc = Scout(x, y, theta, name, self.scouts, self.behaviors) |
265 |
if (newSc.valid):
|
266 |
# successful
|
267 |
self.scouts[newSc.name] = newSc
|
268 |
self.addScoutBox(newSc.name)
|
269 |
# alert user spawn successful
|
270 |
wx.MessageBox(u"Scout '%s' created successfully at (%d,%d,%d\u00B0)"
|
271 |
%(newSc.name, newSc.x, newSc.y, newSc.theta), |
272 |
"Scout Created", wx.OK | wx.ICON_INFORMATION)
|
273 |
|
274 |
else:
|
275 |
#failed to create scout
|
276 |
wx.MessageBox("Scout Creation failed :( Check for duplicate name",
|
277 |
"Add Scout failed", wx.OK | wx.ICON_ERROR)
|
278 |
|
279 |
def removeScout(self, name): |
280 |
sct = self.scouts[name]
|
281 |
sct.killSelf() |
282 |
if (sct.valid == False): |
283 |
# successful, remove from the dictionary
|
284 |
del self.scouts[name] |
285 |
# delete the refresh the display
|
286 |
self.mainArea.Hide(self.sizer[name]) #required by wx before remove |
287 |
self.mainArea.Remove(self.sizer[name]) |
288 |
del self.sizer[name] |
289 |
self.window.Layout()
|
290 |
self.window.Refresh()
|
291 |
self.window.Update()
|
292 |
else:
|
293 |
raise Exception |
294 |
|
295 |
# runPressed
|
296 |
# change UI display and invoke change Behavior in scout
|
297 |
def changeBehavior(self, name, currBehaviorLabel, |
298 |
pauseButton, newBehavior): |
299 |
|
300 |
# to handle user pressing "Run" during pause
|
301 |
if (newBehavior != "Pause" and self.scouts[name].paused == True): |
302 |
self.correctPauseButton(name,
|
303 |
pauseButton, pauseToResume=True)
|
304 |
|
305 |
currBehaviorLabel.SetLabel(" | Current Behavior: %s"%newBehavior)
|
306 |
scout = self.scouts[name]
|
307 |
scout.changeBehavior(newBehavior) |
308 |
self.correctTeleopButton(None) |
309 |
|
310 |
|
311 |
def buttonDown(button): |
312 |
return button.GetValue()
|
313 |
|
314 |
def pauseResumeScout(self, name, pauseButton, currBehaviorLabel, dropMenu): |
315 |
if (pauseButton.GetValue() == True): # |
316 |
# change behavior to Pause
|
317 |
self.changeBehavior(name, currBehaviorLabel, pauseButton, "Pause") |
318 |
# change button to "Resume" & label to "Pause"
|
319 |
currBehaviorLabel.SetLabel("Pause")
|
320 |
self.correctPauseButton(name,
|
321 |
pauseButton, pauseToResume=False)
|
322 |
else:
|
323 |
# resume
|
324 |
# change behavior to whatever is in the drop down menu
|
325 |
self.changeBehavior(name, currBehaviorLabel, pauseButton,
|
326 |
dropMenu.GetStringSelection()) |
327 |
self.correctPauseButton(name,
|
328 |
pauseButton, pauseToResume=True)
|
329 |
|
330 |
def teleop(self, name): |
331 |
self.correctTeleopButton(name)
|
332 |
self.scouts[name].teleop()
|
333 |
|
334 |
def sonar_viz(self, name, sonar_vizButton): |
335 |
if (sonar_vizButton.GetValue() == True): |
336 |
# turn on the sonar viz
|
337 |
self.scouts[name].sonar_viz("on") |
338 |
else:
|
339 |
# turn off sonar viz
|
340 |
self.scouts[name].sonar_viz("off") |
341 |
|
342 |
############################ UI stuff here ###########################
|
343 |
|
344 |
def initUI(self): |
345 |
self.allTeleopButtons = {}
|
346 |
self.initAddScoutArea()
|
347 |
|
348 |
def correctTeleopButton(self, teleopingName): |
349 |
for name in self.allTeleopButtons: |
350 |
if name == teleopingName:
|
351 |
self.allTeleopButtons[name].SetValue(True) |
352 |
else:
|
353 |
self.allTeleopButtons[name].SetValue(False) |
354 |
|
355 |
|
356 |
def correctPauseButton(self, name, pauseButton, pauseToResume): |
357 |
if (pauseToResume):
|
358 |
print "correcting button!" |
359 |
self.scouts[name].paused = False |
360 |
pauseButton.SetValue(False) # unpress it |
361 |
pauseButton.SetLabel("Pause")
|
362 |
else:
|
363 |
self.scouts[name].paused = True |
364 |
pauseButton.SetValue(True) # press it |
365 |
pauseButton.SetLabel("Resume")
|
366 |
|
367 |
# the labels and input boxes for adding a scout through GUI
|
368 |
def initAddScoutArea(self): |
369 |
# all the layout stuff copied over: using grid layout
|
370 |
# button callbacks are changed
|
371 |
self.totalCols = 8 |
372 |
self.window = wx.ScrolledWindow(self, style=wx.VSCROLL) |
373 |
self.mainArea = wx.GridSizer(cols=1) |
374 |
sizer = wx.FlexGridSizer(rows=4, cols=self.totalCols, hgap=5, vgap=5) |
375 |
|
376 |
# Labels
|
377 |
blankText = wx.StaticText(self.window, label="") |
378 |
newScout = wx.StaticText(self.window, label="New Scout") |
379 |
newScoutName = wx.StaticText(self.window, label="Name:") |
380 |
startXTitle = wx.StaticText(self.window, label="X:") |
381 |
startYTitle = wx.StaticText(self.window, label="Y:") |
382 |
startThetaTitle = wx.StaticText(self.window, label="Rad:") |
383 |
|
384 |
# Inputs
|
385 |
newScoutInput = wx.TextCtrl(self.window)
|
386 |
startX = wx.lib.agw.floatspin.FloatSpin(self.window, min_val=0, digits=5) |
387 |
startY = wx.lib.agw.floatspin.FloatSpin(self.window, min_val=0, digits=5) |
388 |
startTheta = wx.lib.agw.floatspin.FloatSpin(self.window, min_val=0, digits=5) |
389 |
addButton = wx.Button(self.window, id=wx.ID_ADD)
|
390 |
|
391 |
# Pretty Stuff
|
392 |
hLine = wx.StaticLine(self.window, size=(600, 5)) |
393 |
bottomHLine = wx.StaticLine(self.window, size=(600, 5)) |
394 |
|
395 |
# Row 0: just the label add scout
|
396 |
sizer.Add(newScout) |
397 |
for i in range(7): |
398 |
sizer.AddStretchSpacer(1)
|
399 |
# Row 1: input(name), x coord, y coord, rad,
|
400 |
sizer.AddMany([newScoutName, (newScoutInput, 0, wx.EXPAND), startXTitle,
|
401 |
startX, startYTitle, startY, startThetaTitle, startTheta]) |
402 |
# Row 2: just the add button to the right
|
403 |
for i in range(7): |
404 |
sizer.AddStretchSpacer(1)
|
405 |
sizer.Add(addButton) |
406 |
# Row 3
|
407 |
|
408 |
# Events
|
409 |
addButton.Bind(wx.EVT_BUTTON, lambda event: self.addScout( |
410 |
startX, startY, startTheta, newScoutInput)) |
411 |
|
412 |
sizer.AddGrowableCol(idx=1)
|
413 |
self.mainArea.Add(sizer, proportion=1, flag=wx.ALL|wx.EXPAND, border=10) |
414 |
self.window.SetSizer(self.mainArea) |
415 |
self.sizer = defaultdict()
|
416 |
self.window.Layout()
|
417 |
|
418 |
# make the scout1's controller
|
419 |
self.addScoutBox("scout1"); |
420 |
|
421 |
|
422 |
|
423 |
# copied over from old GUI
|
424 |
def addScoutBox(self, name): |
425 |
self.sizer[name] = wx.FlexGridSizer(rows=2, cols=5, hgap=5, vgap=5) |
426 |
# Labels
|
427 |
scoutName = wx.StaticText(self.window, label="Scout: %s"%name) |
428 |
behaviorLabel = wx.StaticText(self.window, label="Behavior: ") |
429 |
currBehaviorLabel = wx.StaticText(self.window,
|
430 |
label=" | Current Behavior: Slacking off")
|
431 |
|
432 |
# Inputs
|
433 |
# drop down menue
|
434 |
scoutChoices = wx.Choice(self.window,
|
435 |
choices=self.behaviors.getBehaviors())
|
436 |
# buttons
|
437 |
pauseButton = wx.ToggleButton(self.window, label="Pause") |
438 |
runButton = wx.Button(self.window, label="Run") |
439 |
killButton = wx.Button(self.window, label="Kill") |
440 |
teleopButton = wx.ToggleButton(self.window, label="Teleop") |
441 |
sonar_vizButton = wx.ToggleButton(self.window, label="sonar viz") |
442 |
self.allTeleopButtons[name] = teleopButton
|
443 |
# row 0
|
444 |
self.sizer[name].Add(scoutName)
|
445 |
self.sizer[name].Add(currBehaviorLabel, wx.EXPAND | wx.ALIGN_RIGHT)
|
446 |
self.sizer[name].AddStretchSpacer(1) |
447 |
self.sizer[name].Add(killButton, wx.ALIGN_RIGHT)
|
448 |
self.sizer[name].Add(sonar_vizButton)
|
449 |
|
450 |
# row 1
|
451 |
self.sizer[name].Add(behaviorLabel)
|
452 |
self.sizer[name].Add(scoutChoices, wx.EXPAND)
|
453 |
self.sizer[name].Add(runButton)
|
454 |
self.sizer[name].Add(pauseButton, wx.ALIGN_RIGHT)
|
455 |
self.sizer[name].Add(teleopButton)
|
456 |
# Events
|
457 |
killButton.Bind(wx.EVT_BUTTON, lambda event: self.removeScout(name)) |
458 |
runButton.Bind(wx.EVT_BUTTON, |
459 |
lambda event: self.changeBehavior(name, currBehaviorLabel, |
460 |
pauseButton, # needed to handle press "run" during pause
|
461 |
scoutChoices.GetStringSelection())) |
462 |
pauseButton.Bind(wx.EVT_TOGGLEBUTTON, |
463 |
lambda event: self.pauseResumeScout(name, pauseButton, |
464 |
currBehaviorLabel, scoutChoices)) |
465 |
teleopButton.Bind(wx.EVT_TOGGLEBUTTON, |
466 |
lambda event: self.teleop(name)) |
467 |
sonar_vizButton.Bind(wx.EVT_TOGGLEBUTTON, |
468 |
lambda event:
|
469 |
self.sonar_viz(name, sonar_vizButton))
|
470 |
self.mainArea.Add(self.sizer[name], proportion=1, |
471 |
flag=wx.ALL | wx.EXPAND, border=10)
|
472 |
self.window.Layout()
|
473 |
return True |
474 |
|
475 |
|
476 |
|
477 |
if __name__ == '__main__': |
478 |
# open up GUI
|
479 |
window = Window(title="Colony Scout Manager")
|
480 |
window.MainLoop() |