Statistics
| Branch: | Revision:

root / scout / scoutsim / GUI.py @ cfef1cdc

History | View | Annotate | Download (17.3 KB)

1 01f09975 Yuyang Guo
#!/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 6ee555a3 Priya
import sys
9 01f09975 Yuyang Guo
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 6350051e Alex
import os
23 01f09975 Yuyang Guo
roslib.load_manifest("scoutsim")
24
25
# scoutsim imports
26
from scoutsim.srv import *
27
28
from collections import defaultdict
29
30 9a4d8398 Yuyang Guo
31
class Behaviors(object):
32
    def __init__(self):
33 cfef1cdc Yuyang Guo
        self.behaviors = []
34
        self.loadBehaviorList()
35 9a4d8398 Yuyang Guo
    # this takes advantage of the fact that our behavior list start at 1    
36 cfef1cdc Yuyang Guo
    #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 9a4d8398 Yuyang Guo
    def getNumber(self, behaviorName):
66 cfef1cdc Yuyang Guo
        if (behaviorName in self.behaviors):
67
            return self.behaviors.index(behaviorName)
68 9a4d8398 Yuyang Guo
    
69
    def getName(self, index):
70
        if (0 <= index < len(self.Behavior)):
71 cfef1cdc Yuyang Guo
            return self.behaviors[index]
72 9a4d8398 Yuyang Guo
        else:
73
            return -1
74
    
75
    def getBehaviors(self):
76
        # "Pause" is not considered a behavior in GUI
77 cfef1cdc Yuyang Guo
        return self.behaviors[1:]
78 9a4d8398 Yuyang Guo
79 01f09975 Yuyang Guo
# each scout is represented by this class
80
class Scout(object):
81
    numOfScouts = 0 # class variable keeping track of scouts
82
    
83 cfef1cdc Yuyang Guo
    def __init__(self, x=0, y=0, theta=0, name=u"", behaviors=None,
84 01f09975 Yuyang Guo
                       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 9a4d8398 Yuyang Guo
        self.paused = False
95 01f09975 Yuyang Guo
        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 cfef1cdc Yuyang Guo
        self.behaviors = behaviors
102
103 01f09975 Yuyang Guo
        # 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 9a4d8398 Yuyang Guo
   
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 01f09975 Yuyang Guo
142 9a4d8398 Yuyang Guo
            # the following lines causes lag and does not solve real issues
143
            # first unregister the node
144 1e52c76b Yuyang Guo
            cmd = "rosnode kill /%sBehavior"%self.name
145
            temp = subprocess.Popen(cmd, shell=True)
146
            temp.wait() 
147 9a4d8398 Yuyang Guo
            # this node loses contact but still is not cleaned up in rosnode
148
            # however, this should not affect usage at all.
149 01f09975 Yuyang Guo
        
150 9a4d8398 Yuyang Guo
    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 01f09975 Yuyang Guo
        # do rosprocess calls for new behavior
158 1e52c76b Yuyang Guo
        roscommand = ("rosrun libscout libscout %s %s"%
159 cfef1cdc Yuyang Guo
                            (self.behaviors.getNumber(self.behavior), self.name))
160 1e52c76b Yuyang Guo
        self.process = subprocess.Popen(roscommand, shell=True)
161 01f09975 Yuyang Guo
162 ab8736ac Yuyang Guo
    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 1e52c76b Yuyang Guo
    
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 ab8736ac Yuyang Guo
184 01f09975 Yuyang Guo
    def killSelf(self):
185
        # terminate its current behavior
186 9a4d8398 Yuyang Guo
        self.terminateOldBehavior()
187
        
188 01f09975 Yuyang Guo
        # 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 ab8736ac Yuyang Guo
            print "warning: kill scout unsuccessful" 
197 01f09975 Yuyang Guo
            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 6ee555a3 Priya
        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 01f09975 Yuyang Guo
        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 9a4d8398 Yuyang Guo
        #FIXME: these arguments are not right...fix them!!!
252 cfef1cdc Yuyang Guo
        self.behaviors = Behaviors()
253 01f09975 Yuyang Guo
        self.scouts["scout1"] = Scout(x=0, y=0, theta=0, name="scout1",
254 cfef1cdc Yuyang Guo
                                      behaviors=self.behaviors,
255 01f09975 Yuyang Guo
                                      Scouts = self.scouts, oninit=True)
256 cfef1cdc Yuyang Guo
    
257 01f09975 Yuyang Guo
    # 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 cfef1cdc Yuyang Guo
        newSc = Scout(x, y, theta, name, self.scouts, self.behaviors)
265 01f09975 Yuyang Guo
        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 9a4d8398 Yuyang Guo
            # 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 01f09975 Yuyang Guo
            del self.sizer[name]
289
            self.window.Layout()
290
            self.window.Refresh()
291
            self.window.Update()
292
        else:
293
            raise Exception
294 ab8736ac Yuyang Guo
    
295
    # runPressed
296 9a4d8398 Yuyang Guo
    # 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 ab8736ac Yuyang Guo
        self.correctTeleopButton(None)
309 9a4d8398 Yuyang Guo
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 ab8736ac Yuyang Guo
330
    def teleop(self, name):
331
        self.correctTeleopButton(name)
332
        self.scouts[name].teleop()
333 9a4d8398 Yuyang Guo
334 1e52c76b Yuyang Guo
    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 01f09975 Yuyang Guo
    ############################ UI stuff here ###########################
343
    
344
    def initUI(self):
345 ab8736ac Yuyang Guo
        self.allTeleopButtons = {}
346 01f09975 Yuyang Guo
        self.initAddScoutArea()
347 ab8736ac Yuyang Guo
    
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 01f09975 Yuyang Guo
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 1e52c76b Yuyang Guo
    
421
    
422
423 01f09975 Yuyang Guo
    # 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 9a4d8398 Yuyang Guo
        scoutName = wx.StaticText(self.window, label="Scout: %s"%name)
428 01f09975 Yuyang Guo
        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 9a4d8398 Yuyang Guo
        scoutChoices = wx.Choice(self.window, 
435 cfef1cdc Yuyang Guo
                                    choices=self.behaviors.getBehaviors())
436 01f09975 Yuyang Guo
        #   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 1e52c76b Yuyang Guo
        sonar_vizButton = wx.ToggleButton(self.window, label="sonar viz")
442 ab8736ac Yuyang Guo
        self.allTeleopButtons[name] = teleopButton
443 01f09975 Yuyang Guo
        # 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 1e52c76b Yuyang Guo
        self.sizer[name].Add(sonar_vizButton)
449 01f09975 Yuyang Guo
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 9a4d8398 Yuyang Guo
        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 ab8736ac Yuyang Guo
        teleopButton.Bind(wx.EVT_TOGGLEBUTTON, 
466
                                lambda event: self.teleop(name))
467 1e52c76b Yuyang Guo
        sonar_vizButton.Bind(wx.EVT_TOGGLEBUTTON, 
468
                                lambda event: 
469
                                    self.sonar_viz(name, sonar_vizButton))
470 01f09975 Yuyang Guo
        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()