Project

General

Profile

Statistics
| Branch: | Revision:

root / scout / scoutsim / GUI.py @ 9873e344

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