Example #1
0
class Terminal(Frame):
	def __init__(self, master=None):
		Frame.__init__(self, master)
		self.pack()
		self.CreateWidgets()
		self.prompt = '>>> '
		configfile = open('adminclientconfig.txt', 'r')
		hostname = configfile.readline().strip()
		port = int(configfile.readline().strip())
		username = configfile.readline().strip()
		password = configfile.readline().strip()
		self.conn = Connection(hostname, port, username, password
						,self.ReceiveMessage
						,lambda: self.ReceiveMessage("connection successful")
						,lambda: self.ReceiveMessage("ERROR!!!!"))
	def destroy(self):
		self.conn.Shutdown()
		Frame.destroy(self)
	def CreateWidgets(self):
		self.text = ScrolledText(self, state=DISABLED, height=30)
		self.text["fg"] = "white"
		self.text["bg"] = "black"
		self.text.pack()
		self.entry = Entry(self)
		self.entry["fg"] = "white"
		self.entry["bg"] = "black"
		self.entry.pack(fill=X,pady=0)
		self.entry.bind("<Key-Return>", self.SendMessage)
#		self.entry.bind("<Key-Tab>", lambda _: self.entry.insert(INSERT, "\t"))
	def SendMessage(self, event):
		data = self.entry.get()
		self.entry.delete(0, END)
		self.conn.OnCommand(data, self.OnResult)
		self.ReceiveMessage(self.prompt + data)	# echo
	def ReceiveMessage(self, data):
		self.text.config(state=NORMAL)
		self.text.insert(END, data+"\n")
		self.text.config(state=DISABLED)
		self.text.yview_pickplace('end')
	def OnResult(self, more):
		if more:
			self.prompt = '... '
		else:
			self.prompt = '>>> '
Example #2
0
class App: 
    def __init__(self, master):
        self.master = master
        
        self.file = 'grid.csv'
        
        self.ownZepName = "goud"
        
        self.updatingFlag = False
        
        self.btnUpPressed = False
        self.btnDownPressed = False
        self.btnLeftPressed = False
        self.btnRightPressed = False
        self.btnPlusPressed = False
        self.btnMinusPressed = False
        
        #keyListener aanzetten
        master.bind("<Key>", self.keyPressed)
        master.bind("<KeyRelease>", self.keyReleased)
        
        leftFrame = Frame(master, width = 200, height = 640)
        leftFrame.grid(row = 0, column = 0)
        
        debugFrame = Frame(leftFrame, width = 200, height = 400)
        debugFrame.grid(row = 0, column = 0)
        controlFrame = Frame(leftFrame, width = 200, height = 200)
        controlFrame.grid(row = 1, column = 0, pady = 10)
        
        rasterFrame = Frame(master, width = 600, height = 640)
        rasterFrame.grid(row = 0, column = 1)
        
        #Scrolledtext in leftTopFrame
        self.scrDebug = ScrolledText(debugFrame, wrap = WORD, state = "disabled", fg = "dark red", width=80)
        self.scrDebug.grid(row = 0, column = 0, padx = 10, pady = 10)
        
        #Buttons
        #simulator
        self.btnToggleSimu = Button(controlFrame, text = "Simulator", width = 14, bg = 'gray85', command = lambda: self.toggleSimulator())
        self.btnToggleSimu.grid(row = 3, column = 2)
        
        self.btnMoveToSimu = Button(controlFrame, text = "Ga naar (Sim)", width = 14, bg = 'gray85', command = lambda: self.moveTo(Name = "goudsimu"))
        self.btnMoveToSimu.grid(row = 1, column = 4)
        
        self.btnHeightSimu = Button(controlFrame, text = "Kies hoogte (Sim)", width = 14, bg = 'gray85', command = lambda: self.setGewensteHoogte(Name ="goudsimu"))
        self.btnHeightSimu.grid(row = 2, column = 4)
        
        #hoogte
        self.gemetenHoogteString = StringVar()
        self.gemetenHoogteString.set(str(0))
        self.lblGemetenHoogte = Label(controlFrame, text="Gemeten Hoogte:  ", anchor = "w")
        self.lblGemetenHoogteVar = Label(controlFrame, textvariable = self.gemetenHoogteString, width = 20)
        self.lblGemetenHoogte.grid(row=0, column=2)
        self.lblGemetenHoogteVar.grid(row=0, column=3)
        
        #move to
        self.btnMoveTo = Button(controlFrame, text="Ga naar (Zep)", bg = 'gray85', width = 14, command = lambda: self.moveTo())
        self.btnMoveTo.grid(row=1,column=2)
        self.txtMoveTo = Entry(controlFrame, width=24)
        self.txtMoveTo.grid(row=1, column=3)
        self.txtMoveTo.bind('<Return>', self.moveTo)
        
        #hoogte 
        self.btnHeight = Button(controlFrame, text="Kies hoogte (Zep)", bg = 'gray85', width = 14, command = lambda: self.setGewensteHoogte())
        self.btnHeight.grid(row=2,column=2)
        self.txtHeight = Entry(controlFrame, width=24)
        self.txtHeight.grid(row=2, column=3)
        self.txtHeight.bind('<Return>', self.setGewensteHoogte)
        
        #images
        self.display = Canvas(rasterFrame, width=600, height=570, bd=0, highlightthickness=0)
        self.display.grid(row=0, column = 0, sticky=W+E+N+S)
        
        foundFigures = Label(controlFrame, text = "Herkende figuren:")
        foundFigures.grid(row = 0, column = 0)        
        self.display2 = Canvas(controlFrame, width = 220, height=165, bd=2, relief = "groove", highlightthickness=0)
        self.display2.grid(row=1, column = 0, sticky=W+E+N+S, rowspan=12)
        self.latestphoto = Image.new("RGB", (220,165), (150,150,150))        
        self.latestImage = ImageTk.PhotoImage(self.latestphoto)
        self.display2.create_image(0, 0, image=self.latestImage, anchor=NW)
        
        #goal
        original = Image.open('goalPin.png')
        resized = original.resize((60,60),Image.ANTIALIAS)
        self.goalImage = ImageTk.PhotoImage(resized)
        
        self.makeBackground()
        self.initZeppelins()
        self.paintCanvas()
        
        self.sim = None
        mq.setGUI(self)
                
    def initZeppelins(self):
        self.zeppelins = []
        self.goal = (-100,-100)
#         self.zeppelins.append(AbstractZeppelin('red', 'simu'))
        self.zeppelins.append(AbstractZeppelin('#EBB400', self.ownZepName))
                
    def convToPixelCoords(self, pos):
        cmHeight = 34.6410162
        cmWidth = 40.0
        xcm, ycm = pos
        x = self.evenXStart + (xcm/cmWidth)*self.triangleWidth
        y = self.yStart + (ycm/cmHeight)*self.triangleHeight
        result = (x,y)
        return result
    
    def createPhoto(self, cvresults):
        self.latestphoto = Image.new("RGB", (220,165), (150,150,150))
        cv = eval(cvresults)
        width = cv[0]
        height = cv[1]
        figures = cv[2]
        coordinates = cv[3]
        for i in xrange(0,len(figures)):
            j = self.allShapes.index(figures[i])
            image = self.shapeImages[j]
            xcoord = int(coordinates[i][0]/(width*1.0)*220)
            ycoord = int(coordinates[i][1]/(height*1.0)*165)
            self.latestphoto.paste(image, (xcoord-12, ycoord-12), mask = image)
               
        self.latestImage = ImageTk.PhotoImage(self.latestphoto)
        self.display2.create_image(0, 0, image=self.latestImage, anchor=NW)
    
    def makeBackground(self):
        #rooster inlezen:
        f = open("../positioning/"+ str(self.file), 'r')
        shapesText = f.read()
        self.raster = []
        self.tabletLocations = []
        nrows = 0
        ncol = 0
        for line in shapesText.split("\n"):
            temp = line.split(",")
            if not len(temp) == 2:
                nrows += 1
                if ncol == 0:
                    ncol = len(temp)
                for s in temp:
                    self.raster.append(s.strip())
            else:
                self.tabletLocations.append((int(temp[0]), int(temp[1])))
        f.close()
        
        tempWidth1 = 600/ncol
        tempHeight1 = int(round((math.sqrt(tempWidth1**2 - (tempWidth1/2)**2)), 0))
        
        tempHeight2 = 570/nrows+2
        tempWidth2 = int(round((math.sqrt(4/3 * tempHeight2**2)),0))
        
        #raster
        self.resizedRaster = Image.new("RGB", (600,570), (240,240,240))
        #vormpjes
        self.allShapes = ['BC','BH','BR','BS','GC','GH','GR','GS','RC','RH','RR','RS','WC','WH','WR','WS','YC','YH','YR','YS']
        self.shapeImages = []
        
        for i in range(20):
            imgFile = "vormpjes/" + self.allShapes[i] + ".png"
            original = Image.open(imgFile)
            self.shapeImages.append(original.resize((24, 24),Image.ANTIALIAS))
            
        original = Image.open("tablet.png")
        self.tabletIm = original.resize((40,40),Image.ANTIALIAS)
            
        self.xlen = ncol
        self.ylen = nrows
        self.triangleWidth = min(tempWidth1, tempWidth2)
        self.triangleHeight = min(tempHeight1, tempHeight2)
        self.evenXStart = (600-((ncol)*self.triangleWidth))/2 + self.triangleWidth/4
        self.oddXStart = self.evenXStart + self.triangleWidth/2
        self.yStart = (600-((nrows)*self.triangleHeight))/2 + self.triangleHeight/4
        
        
        draw = ImageDraw.Draw(self.resizedRaster)
        #grid tekenen
        for y in range(self.ylen):
            for x in range(self.xlen):
                ycoord = self.yStart + y*self.triangleHeight
                
                zelf = self.raster[y*self.xlen + x] != "XX"
                if y>0: 
                    boven = self.raster[(y-1)*self.xlen + x] != "XX"
                if y<self.ylen-1:
                    onder = self.raster[(y+1)*self.xlen + x] != "XX"
                if y>0 and x < self.xlen-1: 
                    oddboven = self.raster[(y-1)*self.xlen + x+1] != "XX"
                if y<self.ylen-1 and x < self.xlen-1:
                    oddonder = self.raster[(y+1)*self.xlen + x+1] != "XX"
                if x<self.xlen-1:
                    naast = self.raster[y*self.xlen + x+1] != "XX"
            
                if y % 2 == 0:
                    xcoord = self.evenXStart + x*self.triangleWidth
                    if x < self.xlen-1 and naast and zelf:
                        draw.line((xcoord, ycoord, xcoord+self.triangleWidth, ycoord), fill = 0)
                    if y < self.ylen-1 and onder and zelf:
                        draw.line((xcoord, ycoord, xcoord+self.triangleWidth/2, ycoord+self.triangleHeight), fill = 0)
                    if y > 0 and boven and zelf:
                        draw.line((xcoord, ycoord, xcoord+self.triangleWidth/2, ycoord-self.triangleHeight), fill = 0)
                else:
                    xcoord = self.oddXStart + x*self.triangleWidth
                    if x < self.xlen-1 and naast and zelf:
                        draw.line((xcoord, ycoord, xcoord+self.triangleWidth, ycoord), fill = 0)
                    if y < self.ylen-1 and x < self.xlen-1 and oddonder and zelf:
                        draw.line((xcoord, ycoord, xcoord+self.triangleWidth/2, ycoord+self.triangleHeight), fill = 0)
                    if y > 0 and x < self.xlen-1 and oddboven and zelf:
                        draw.line((xcoord, ycoord, xcoord+self.triangleWidth/2, ycoord-self.triangleHeight), fill = 0)
                
        del draw
        
        for loc in self.tabletLocations:
            conv = self.convToPixelCoords((loc[0]/10, loc[1]/10))
            self.resizedRaster.paste(self.tabletIm, (int(conv[0])-20, int(conv[1])-20), mask = self.tabletIm)
        
        #vormpjes tekenen
        for y in range(self.ylen):
            for x in range(self.xlen):
                index = y*self.xlen + x
                if y % 2 == 0:
                    xcoord = self.evenXStart + x*self.triangleWidth
                else:
                    xcoord = self.oddXStart + x*self.triangleWidth
                ycoord = self.yStart + y*self.triangleHeight
                shape = self.raster[index]
                if shape != 'XX':
                    image = self.shapeImages[self.allShapes.index(shape)]
                    self.resizedRaster.paste(image, (xcoord-12, ycoord-12), mask = image)
    
        self.rasterImage = ImageTk.PhotoImage(self.resizedRaster)
        
    def updatePath(self):
        self.rasterBackup = self.rasterImage
        draw = ImageDraw.Draw(self.resizedRaster)
        for z in self.zeppelins:
            length = len(z.locations)
            if length > 1:
                prev = self.convToPixelCoords(z.locations[length-2])
                current = self.convToPixelCoords(z.locations[length-1])
                draw.line((prev[0], prev[1], current[0], current[1]), fill=z.color, width = 3)
        self.rasterImage = ImageTk.PhotoImage(self.resizedRaster)
        del draw
            
        
    def paintCanvas(self):
        #clear the canvas
        #self.display.delete('all')
        #rooster tekenen
        self.updatePath()
        self.display.create_image(0, 0, image=self.rasterImage, anchor=NW)
        
        #Testcode voor zeppelin locatie
        for z in self.zeppelins:
            if z.orientationFound:
                point1x = self.convToPixelCoords(z.location)[0]+16*math.sin(math.radians(z.orientation + 20))
                point1y = self.convToPixelCoords(z.location)[1]+16*math.cos(math.radians(z.orientation + 20))
                point2x = self.convToPixelCoords(z.location)[0]+16*math.sin(math.radians(z.orientation - 20))
                point2y = self.convToPixelCoords(z.location)[1]+16*math.cos(math.radians(z.orientation - 20))
                point3x = self.convToPixelCoords(z.location)[0]+28*math.sin(math.radians(z.orientation))
                point3y = self.convToPixelCoords(z.location)[1]+28*math.cos(math.radians(z.orientation))
                arrowPoints = [point1x, point1y, point2x, point2y, point3x, point3y]
                self.display.create_polygon(arrowPoints, fill=z.color, outline='black', width = 1)
            self.display.create_oval(self.convToPixelCoords(z.location)[0]-12, self.convToPixelCoords(z.location)[1]-12,self.convToPixelCoords(z.location)[0]+12, self.convToPixelCoords(z.location)[1]+12, fill=z.color)
                    
        self.display.create_image(self.convToPixelCoords(self.goal)[0]+6, self.convToPixelCoords(self.goal)[1]-18, image = self.goalImage, anchor=CENTER)
    
    def toggleSimulator(self):
        if self.sim == None:
            enemy = "goudsimu"
            self.zeppelins.append(AbstractZeppelin("red", enemy))
            mq.initEnemy(enemy)
            self.sim = simulator.simulator(100,100, enemy)
            return
        self.sim.toggleActive()
    
    def updateGoal(self, location, tablet):
        self.debugPrint("Nieuw doel voor simulator: " + str(tablet) + "   " + str(location))
        self.goal = self.convToPixelCoords(location)
        self.paintCanvas()
        
    def updateLocation(self, location, n):
        self.debugPrint("Nieuwe locatie voor " + n + " ontvangen: " + str(location))
        for z in self.zeppelins:
            if z.name == n:
                z.updateLocation((location[0]/10, location[1]/10))
        self.paintCanvas()
        
    def updateHeight(self, height, n):
        self.debugPrint("Nieuwe hoogte voor " + n + " ontvangen: " + str(height))
        if self.ownZepName == n:
            self.gemetenHoogteString.set(str(height))
        
    def updateAngle(self, angle, n):
        self.debugPrint("Nieuwe orientatie voor " + n + " ontvangen: " + str(angle) + " graden")
        for z in self.zeppelins:
            if z.name == n:
                z.updateAngle(angle)
        self.paintCanvas()
    
    def showCvResults(self, body):
        self.debugPrint("Nieuwe foto vertaling ontvangen: " + body)
        self.createPhoto(body)
       
    #gewenste hoogte aanpassen    
    def setGewensteHoogte(self, event = None, Name = "goud"):
        x = self.txtHeight.get()
        self.txtHeight.delete(0, END)
        self.master.focus()
        try:
            x = int(x)
        except:
            return
        if isinstance(x, int) and x > 0 and x < 8000:
            global neededHeight
            neededHeight = x
            message = "Hoogte instellen op " + str(neededHeight) + " aangevraagd"
            self.debugPrint(message)
            mq.elevate(x, Name)
            
    #gewenste hoogte aanpassen    
    def moveTo(self, event = None, Name = "goud"):
        st = self.txtMoveTo.get()
        self.txtMoveTo.delete(0, END)
        self.master.focus()
        try:
            xst, yst = st.split(',')
            x = int(xst)
            y = int(yst)
        except:
            return
        if isinstance(x, int) and isinstance(y, int):
            message = "Bewegen naar (" + str(x) + "," + str(y) + ") aangevraagd"
            self.debugPrint(message)
            self.goal = x/10,y/10
            self.paintCanvas()
            mq.moveTo(x, y, Name)
     
    #tekst weergeven in debug venster    
    def debugPrint(self, tekst):
        self.scrDebug.config(state = "normal")
        self.scrDebug.insert(END, ">> " + tekst + "\n")
        self.scrDebug.config(state = "disabled")
        self.scrDebug.yview_pickplace("end")
        
    def toggleAutomaticPilot(self):
        if not self.connected:
            return
        self.debugPrint("Automatische piloot toggle aangevraagd")
        self.client.toggleAutomaticPilot() 
        
    def createClient(self):
        try:
            self.client = cl(self, self.ownZepName)
            self.zeppelins.append(AbstractZeppelin('red', self.ownZepName, self, self.client))
            self.connected = True
            self.connectedString.set("Verbonden")
            self.lblConnected.config(fg = "green")
            self.debugPrint("Verbonden met Raspberry Pi")
        except:
            self.debugPrint("Verbinding met Rapsberry Pi niet mogelijk:\n    -Staat de Raspberry Pi aan?\n    -Staat de server aan?\n    -Zit deze computer op de ad-hoc?")
            
        
    def moveForward(self):
        self.debugPrint("Voorwaarts vliegen aangevraagd")
        mq.setMotor1PWM(100)
        mq.setMotor2PWM(100)
        
    def moveBackward(self):
        self.debugPrint("Achterwaarts vliegen aangevraagd")
        mq.setMotor1PWM(-100)
        mq.setMotor2PWM(-100)
    
    def moveLeft(self):
        self.debugPrint("Links draaien aangevraagd")
        mq.setMotor1PWM(100)
        
    def moveRight(self):
        self.debugPrint("Rechts draaien aangevraagd")
        mq.setMotor2PWM(100)
        
    def moveUp(self):
        self.debugPrint("Omhoog vliegen aangevraagd")
        mq.setMotor3PWM(100)
        
    def moveDown(self):
        self.debugPrint("Omlaag vliegen aangevraagd")
        mq.setMotor3PWM(-100)
        
    def horizontalOff(self):
        self.debugPrint("Horizontale motors stoppen aangevraagd")
        mq.setMotor1PWM(0)
        mq.setMotor2PWM(0)
        
    def verticalOff(self):
        self.debugPrint("Verticale motor stoppen aangevraagd")
        mq.setMotor3PWM(0)
        
    #toetsenbord invoer
    def keyPressed(self, event):
        k = event.keysym
        if k == 'Up':
            if not self.btnUpPressed:
                self.btnUpPressed = True
                self.moveForward()
        elif k == 'Down':
            if not self.btnDownPressed:
                self.btnDownPressed = True
                self.moveBackward()   
        elif k == 'Left':
            if not self.btnLeftPressed:
                self.btnLeftPressed = True
                self.moveLeft()
        elif k == 'Right':
            if not self.btnRightPressed:
                self.btnRightPressed = True
                self.moveRight()
        elif k == 'plus':
            if not self.btnPlusPressed:
                self.btnPlusPressed = True
                self.moveUp()
        elif k == 'minus':
            if not self.btnMinusPressed:
                self.btnMinusPressed = True
                self.moveDown()
            
    def keyReleased(self, event):
        k = event.keysym
        if k == 'Up':
            self.btnUpPressed = False
            self.horizontalOff()
        elif k == 'Down':
            self.btnDownPressed = False
            self.horizontalOff()
        elif k == 'Left':
            self.btnLeftPressed = False
            self.horizontalOff()
        elif k == 'Right':
            self.btnRightPressed = False
            self.horizontalOff()
        elif k == 'plus':
            self.btnPlusPressed = False
            self.verticalOff()
        elif k == 'minus':
            self.btnMinusPressed = False
            self.verticalOff()
Example #3
0
class App: 
    def __init__(self, master):
        self.master = master
        
        self.file = 'grid.csv'
        
        self.ownZepName = "Jack"
        
        self.updatingFlag = False
        
        self.btnUpPressed = False
        self.btnDownPressed = False
        self.btnLeftPressed = False
        self.btnRightPressed = False
        self.btnPlusPressed = False
        self.btnMinusPressed = False
        
        #keyListener aanzetten
        master.bind("<Key>", self.keyPressed)
        master.bind("<KeyRelease>", self.keyReleased)
        
        labelFont = tkFont.Font(size = 16)
        
        leftFrame = Frame(master, width = 200, height = 640)
        leftFrame.grid(row = 0, column = 0)
        
        debugFrame = Frame(leftFrame, width = 200, height = 400)
        debugFrame.grid(row = 0, column = 0)
        controlFrame = Frame(leftFrame, width = 200, height = 200)
        controlFrame.grid(row = 1, column = 0, pady = 20)
        
        rasterFrame = Frame(master, width = 600, height = 640)
        rasterFrame.grid(row = 0, column = 1)
        
        #Scrolledtext in leftTopFrame
        self.scrDebug = ScrolledText(debugFrame, wrap = WORD, state = "disabled", fg = "dark red", width=65)
        self.scrDebug.grid(row = 0, column = 0, padx = 10, pady = 10)
        
        #Buttons
        #hoogte
        self.gemetenHoogteString = StringVar()
        self.gemetenHoogteString.set(str(100.0))
        self.lblGemetenHoogte = Label(controlFrame, text="Gemeten Hoogte:  ", anchor = "w")
        self.lblGemetenHoogteVar = Label(controlFrame, textvariable = self.gemetenHoogteString, width = 20)
        self.lblGemetenHoogte.grid(row=0, column=2)
        self.lblGemetenHoogteVar.grid(row=0, column=3)
        
        #autopilot TODO string
        self.automaticFlag = False
        self.btnAutomaticPilot = Button(controlFrame, text = "Auto-pilot", width = 14, bg = 'gray85', command = lambda: self.toggleAutomaticPilot())
        self.btnAutomaticPilot.grid(row = 1, column = 2)
        
        self.btnTest = Button(controlFrame, text = "Update", width = 14, bg = 'gray85', command = lambda: self.fetchPhoto())
        self.btnTest.grid(row = 3, column = 2)
        
        self.automaticString = StringVar()
        self.automaticString.set("Niet Actief")
        self.lblAutomatic = Label(controlFrame, textvariable = self.automaticString, font = tkFont.Font(size = 14))
        self.lblAutomatic.grid(row = 1, column = 3)
        
        #verbinding 
        self.connected = False;
        self.btnConnect = Button(controlFrame, text = "Verbind", width = 14, bg = 'gray85', command = lambda: self.createClient())
        self.btnConnect.grid(row = 2, column = 2)
        
        self.connectedString = StringVar()
        self.connectedString.set("Niet Verbonden")
        self.lblConnected = Label(controlFrame, textvariable = self.connectedString, font = tkFont.Font(size = 14))
        self.lblConnected.grid(row = 2, column = 3)
        
        #motorinfo
        self.lblmotorUpString = Label(controlFrame, text = "MOTOR U: ", fg = "red", font = labelFont)
        self.lblmotorUpString.grid(row = 0, column = 0)
        self.lblmotorLeftString = Label(controlFrame, text = "MOTOR L: ", fg = "red", font = labelFont)
        self.lblmotorLeftString.grid(row = 1, column = 0)
        self.lblmotorRightString = Label(controlFrame, text = "MOTOR R: ", fg = "red", font = labelFont)
        self.lblmotorRightString.grid(row = 2, column = 0)
        self.lblmotorPWMString = Label(controlFrame, text = "PWM U: ", font = labelFont)
        self.lblmotorPWMString.grid(row = 3, column = 0)
        self.motorLeftString = StringVar()
        self.motorLeftString.set("S")
        self.motorRightString = StringVar()
        self.motorRightString.set("S")
        self.motorUpString = StringVar()
        self.motorUpString.set("S")
        self.motorPWMString = StringVar()
        self.motorPWMString.set("100")
        self.lblmotorUpStringValue = Label(controlFrame, textvariable = self.motorUpString, width = 5, fg = "red", font = labelFont)
        self.lblmotorUpStringValue.grid(row = 0, column = 1)
        self.lblmotorLeftStringValue = Label(controlFrame, textvariable = self.motorLeftString, width = 5, fg = "red", font = labelFont)
        self.lblmotorLeftStringValue.grid(row = 1, column = 1)
        self.lblmotorRightStringValue = Label(controlFrame, textvariable = self.motorRightString, width = 5, fg = "red", font = labelFont)
        self.lblmotorRightStringValue.grid(row = 2, column = 1)
        self.motorPWMStringValue = Label(controlFrame, textvariable = self.motorPWMString, width = 5, font = labelFont)
        self.motorPWMStringValue.grid(row = 3, column = 1)
        
        #self.createClient()
        
        #images
        self.display = Canvas(rasterFrame, width=600, height=570, bd=0, highlightthickness=0)
        self.display.grid(row=0, column = 0, sticky=W+E+N+S)
        
        #goal
        original = Image.open('goalPin.png')
        resized = original.resize((60,60),Image.ANTIALIAS)
        self.goalImage = ImageTk.PhotoImage(resized)
        
        self.makeBackground()
        self.initZeppelins() #kan interactief gebeuren met invoer als namen en bron in debugvenster typen
        self.paintCanvas()
        
    def initZeppelins(self):
        self.zeppelins = []
        self.goal = (100,100)
        #self.zeppelins.append(AbstractZeppelin('green', 'Weppelin', self, randomSimu.randomSimulator(self, 'Weppelin', self.goal[0], self.goal[1])))
    
    def requestUpdate(self, n):
        for z in self.zeppelins:
            if z.name == n:
                z.updateInfo()
                
    def convToPixelCoords(self, pos):
        cmHeight = 34.6410162
        cmWidth = 40.0
        xcm, ycm = pos
        x = self.evenXStart + (xcm/cmWidth)*self.triangleWidth
        y = self.yStart + (ycm/cmHeight)*self.triangleHeight
        result = (x,y)
        return result
    
    def makeBackground(self):
        #rooster inlezen:
        f = open("../positioning/"+ str(self.file), 'r')
        shapesText = f.read()
        lofl = map(lambda l: l.split(","), shapesText.split("\n"))
        self.raster = [val.strip() for subl in lofl for val in subl]
        f.close()
        
        nrows = len(lofl)
        ncol = len(lofl[0])
        
        
        tempWidth1 = 600/ncol
        tempHeight1 = int(round((math.sqrt(tempWidth1**2 - (tempWidth1/2)**2)), 0))
        
        tempHeight2 = 570/nrows+2
        tempWidth2 = int(round((math.sqrt(4/3 * tempHeight2**2)),0))
        
        #raster
        self.resizedRaster = Image.new("RGB", (600,570), (240,240,240))
        #vormpjes
        self.allShapes = ['BC','BH','BR','BS','GC','GH','GR','GS','RC','RH','RR','RS','WC','WH','WR','WS','YC','YH','YR','YS']
        self.shapeImages = []
        
        for i in range(20):
            imgFile = "vormpjes/" + self.allShapes[i] + ".png"
            original = Image.open(imgFile)
            self.shapeImages.append(original.resize((24, 24),Image.ANTIALIAS))
            
        self.xlen = ncol
        self.ylen = nrows
        self.triangleWidth = min(tempWidth1, tempWidth2)
        self.triangleHeight = min(tempHeight1, tempHeight2)
        self.evenXStart = (600-((ncol)*self.triangleWidth))/2 + self.triangleWidth/4
        self.oddXStart = self.evenXStart + self.triangleWidth/2
        self.yStart = (600-((nrows)*self.triangleHeight))/2 + self.triangleHeight/4
        
        
        draw = ImageDraw.Draw(self.resizedRaster)
        #grid tekenen
        for y in range(self.ylen):
            for x in range(self.xlen):
                ycoord = self.yStart + y*self.triangleHeight
                
                zelf = self.raster[y*self.xlen + x] != "XX"
                if y>0: 
                    boven = self.raster[(y-1)*self.xlen + x] != "XX"
                if y<self.ylen-1:
                    onder = self.raster[(y+1)*self.xlen + x] != "XX"
                if y>0 and x < self.xlen-1: 
                    oddboven = self.raster[(y-1)*self.xlen + x+1] != "XX"
                if y<self.ylen-1 and x < self.xlen-1:
                    oddonder = self.raster[(y+1)*self.xlen + x+1] != "XX"
                if x<self.xlen-1:
                    naast = self.raster[y*self.xlen + x+1] != "XX"
            
                if y % 2 == 0:
                    xcoord = self.evenXStart + x*self.triangleWidth
                    if x < self.xlen-1 and naast and zelf:
                        draw.line((xcoord, ycoord, xcoord+self.triangleWidth, ycoord), fill = 0)
                    if y < self.ylen-1 and onder and zelf:
                        draw.line((xcoord, ycoord, xcoord+self.triangleWidth/2, ycoord+self.triangleHeight), fill = 0)
                    if y > 0 and boven and zelf:
                        draw.line((xcoord, ycoord, xcoord+self.triangleWidth/2, ycoord-self.triangleHeight), fill = 0)
                else:
                    xcoord = self.oddXStart + x*self.triangleWidth
                    if x < self.xlen-1 and naast and zelf:
                        draw.line((xcoord, ycoord, xcoord+self.triangleWidth, ycoord), fill = 0)
                    if y < self.ylen-1 and x < self.xlen-1 and oddonder and zelf:
                        draw.line((xcoord, ycoord, xcoord+self.triangleWidth/2, ycoord+self.triangleHeight), fill = 0)
                    if y > 0 and x < self.xlen-1 and oddboven and zelf:
                        draw.line((xcoord, ycoord, xcoord+self.triangleWidth/2, ycoord-self.triangleHeight), fill = 0)
                
        del draw
        
        #vormpjes tekenen
        for y in range(self.ylen):
            for x in range(self.xlen):
                index = y*self.xlen + x
                if y % 2 == 0:
                    xcoord = self.evenXStart + x*self.triangleWidth
                else:
                    xcoord = self.oddXStart + x*self.triangleWidth
                ycoord = self.yStart + y*self.triangleHeight
                shape = self.raster[index]
                if shape != 'XX':
                    image = self.shapeImages[self.allShapes.index(shape)]
                    self.resizedRaster.paste(image, (xcoord-12, ycoord-12), mask = image)
    
        self.rasterImage = ImageTk.PhotoImage(self.resizedRaster)
        
    def updatePath(self):
        self.rasterBackup = self.rasterImage
        draw = ImageDraw.Draw(self.resizedRaster)
        for z in self.zeppelins:
            length = len(z.locations)
            if length > 1:
                prev = self.convToPixelCoords(z.locations[length-2])
                current = self.convToPixelCoords(z.locations[length-1])
                draw.line((prev[0], prev[1], current[0], current[1]), fill=z.color, width = 3)
        self.rasterImage = ImageTk.PhotoImage(self.resizedRaster)
        del draw
            
        
    def paintCanvas(self):
        #clear the canvas
        #self.display.delete('all')
        #rooster tekenen
        self.updatePath()
        self.display.create_image(0, 0, image=self.rasterImage, anchor=NW)
        
        #Testcode voor zeppelin locatie
        for z in self.zeppelins:
            point1x = self.convToPixelCoords(z.location)[0]+16*math.sin(math.radians(z.orientation + 20))
            point1y = self.convToPixelCoords(z.location)[1]+16*math.cos(math.radians(z.orientation + 20))
            point2x = self.convToPixelCoords(z.location)[0]+16*math.sin(math.radians(z.orientation - 20))
            point2y = self.convToPixelCoords(z.location)[1]+16*math.cos(math.radians(z.orientation - 20))
            point3x = self.convToPixelCoords(z.location)[0]+28*math.sin(math.radians(z.orientation))
            point3y = self.convToPixelCoords(z.location)[1]+28*math.cos(math.radians(z.orientation))
            self.display.create_oval(self.convToPixelCoords(z.location)[0]-12, self.convToPixelCoords(z.location)[1]-12,self.convToPixelCoords(z.location)[0]+12, self.convToPixelCoords(z.location)[1]+12, fill=z.color)
            arrowPoints = [point1x, point1y, point2x, point2y, point3x, point3y]
            self.display.create_polygon(arrowPoints, fill=z.color, outline='black', width = 1)
                
        self.display.create_image(self.convToPixelCoords(self.goal)[0]+6, self.convToPixelCoords(self.goal)[1]-18, image = self.goalImage, anchor=CENTER)
        
    #tekst weergeven in debug venster    
    def debugPrint(self, tekst):
        self.scrDebug.config(state = "normal")
        self.scrDebug.insert(END, ">> " + tekst + "\n")
        self.scrDebug.config(state = "disabled")
        self.scrDebug.yview_pickplace("end")
        
    def toggleAutomaticPilot(self):
        if not self.connected:
            return
        self.debugPrint("Automatische piloot toggle aangevraagd")
        self.client.toggleAutomaticPilot() 
        
    def createClient(self):
        try:
            if self.connected == False:
                self.client = cl(self, self.ownZepName)
                self.zeppelins.append(AbstractZeppelin('red', self.ownZepName, self, self.client))
                self.connected = True
                self.connectedString.set("Verbonden")
                self.lblConnected.config(fg = "green")
                self.debugPrint("Verbonden met Raspberry Pi")
            else:
                self.debugPrint("Al verbonden")
        except:
            self.debugPrint("Verbinding met Rapsberry Pi niet mogelijk:\n    -Staat de Raspberry Pi aan?\n    -Staat de server aan?\n    -Zit deze computer op de ad-hoc?")
            
    def disconnect(self):
        self.connected = False
        self.connectedString.set("Niet verbonden")
        self.lblConnected.config(fg = "red")
        
    def fetchPhoto(self):
        if not self.connected or self.automaticFlag:
            return
        self.client.updateInformation()
        
    def moveForward(self):
        if not self.connected or self.automaticFlag:
            return
        self.debugPrint("Voorwaarts vliegen aangevraagd")
        self.client.flyForward()
        
    def moveBackward(self):
        if not self.connected or self.automaticFlag:
            return
        self.debugPrint("Achterwaarts vliegen aangevraagd")
        self.client.flyBackward()
    
    def moveLeft(self):
        if not self.connected or self.automaticFlag:
            return
        self.debugPrint("Links draaien aangevraagd")
        self.client.turnLeft()
        
    def moveRight(self):
        if not self.connected or self.automaticFlag:
            return
        self.debugPrint("Rechts draaien aangevraagd")
        self.client.turnRight()
        
    def moveUp(self):
        if not self.connected or self.automaticFlag:
            return
        self.debugPrint("Omhoog vliegen aangevraagd")
        if(self.correctieFlag):
            self.toggleHeightCorrection()
        self.client.motorUpBackward()
        
    def moveDown(self):
        if not self.connected or self.automaticFlag:
            return
        self.debugPrint("Omlaag vliegen aangevraagd")
        if(self.correctieFlag):
            self.toggleHeightCorrection()
        self.client.motorUpForward()
        
    def horizontalOff(self):
        if not self.connected or self.automaticFlag:
            return
        self.debugPrint("Horizontale motors stoppen aangevraagd")
        self.client.stopHorizontalMotors()
        
    def verticalOff(self):
        if not self.connected or self.automaticFlag:
            return
        self.debugPrint("Verticale motor stoppen aangevraagd")
        self.client.motorUpStop()
        
    #toetsenbord invoer
    def keyPressed(self, event):
        k = event.keysym
        if k == 'Up':
            if not self.btnUpPressed:
                self.btnUpPressed = True
                self.moveForward()
        elif k == 'Down':
            if not self.btnDownPressed:
                self.btnDownPressed = True
                self.moveBackward()   
        elif k == 'Left':
            if not self.btnLeftPressed:
                self.btnLeftPressed = True
                self.moveLeft()
        elif k == 'Right':
            if not self.btnRightPressed:
                self.btnRightPressed = True
                self.moveRight()
        elif k == 'plus':
            if not self.btnPlusPressed:
                self.btnPlusPressed = True
                self.moveUp()
        elif k == 'minus':
            if not self.btnMinusPressed:
                self.btnMinusPressed = True
                self.moveDown()
            
    def keyReleased(self, event):
        k = event.keysym
        if k == 'Up':
            self.btnUpPressed = False
            self.horizontalOff()
        elif k == 'Down':
            self.btnDownPressed = False
            self.horizontalOff()
        elif k == 'Left':
            self.btnLeftPressed = False
            self.horizontalOff()
        elif k == 'Right':
            self.btnRightPressed = False
            self.horizontalOff()
        elif k == 'plus':
            self.btnPlusPressed = False
            self.verticalOff()
        elif k == 'minus':
            self.btnMinusPressed = False
            self.verticalOff()
            
    def updateAutomatic(self, info):
        if info[0]:
            self.debugPrint(str(info[4]))
            
    def updateInfo(self, info):
        global realHeight
        if info[0] != -1:
            self.gemetenHoogteString.set(str(info[0]))
            self.motorUpString.set(info[1])
            
        if info[1] == "V" or info[1] == "A":
            self.lblmotorUpString.config(fg = "green")
            self.lblmotorUpStringValue.config(fg = "green")
        else: 
            self.lblmotorUpString.config(fg = "red")
            self.lblmotorUpStringValue.config(fg = "red")
        
        self.motorLeftString.set(info[2])
        if info[2] == "V" or info[2] == "A":
            self.lblmotorLeftString.config(fg = "green")
            self.lblmotorLeftStringValue.config(fg = "green")
        else: 
            self.lblmotorLeftString.config(fg = "red")
            self.lblmotorLeftStringValue.config(fg = "red")
        
        self.motorRightString.set(info[3])
        if info[3] == "V" or info[3] == "A":
            self.lblmotorRightString.config(fg = "green")
            self.lblmotorRightStringValue.config(fg = "green")
        else: 
            self.lblmotorRightString.config(fg = "red")
            self.lblmotorRightStringValue.config(fg = "red")
        
        self.motorPWMString.set(str(math.ceil(info[4])))
            
        self.automaticFlag = info[6]
        if(not self.automaticFlag):
            self.automaticString = "Niet Actief"
        else:
            self.automaticString = "Actief"
Example #4
0
class App:
    def __init__(self, master):
        self.master = master
        
        self.btnUpPressed = False
        self.btnDownPressed = False
        self.btnLeftPressed = False
        self.btnRightPressed = False
        self.btnPlusPressed = False
        self.btnMinusPressed = False
        
        #keyListener aanzetten
        master.bind("<Key>", self.keyPressed)
        master.bind("<KeyRelease>", self.keyReleased)
        
        labelFont = tkFont.Font(size = 16)
        
        #TOPFRAME: 800x400
        topFrame = Frame(master, width=800,height=400, bg = "blue")
        topFrame.pack(padx=10, pady=10, side = TOP)
        leftTopFrame = Frame(topFrame, bg = "blue")
        leftTopFrame.grid(row = 0, column = 0)
        rightTopFrame = Frame(topFrame, bg = "blue")
        rightTopFrame.grid(row = 0, column = 2)
        middleTopFrame = Frame(topFrame, bg = "blue")
        middleTopFrame.grid(row = 0, column = 1, padx = 10)
        
        #BOTTOMFRAME: 800X200
        bottomFrame = Frame(master, width=800,height=200, bg = "blue")
        bottomFrame.pack(padx=20, pady=10, side = BOTTOM)
        leftBottomFrame = Frame(bottomFrame, bg = "blue")
        leftBottomFrame.pack(side = LEFT)
        rightBottomFrame = Frame(bottomFrame, bg = "blue")
        rightBottomFrame.pack(side = RIGHT)
        leftRightBottomFrame = Frame(rightBottomFrame, bg = "blue")
        leftRightBottomFrame.pack(padx = 30, side = LEFT)
        rightRightBottomFrame = Frame(rightBottomFrame, bg = "blue")
        rightRightBottomFrame.pack(side = RIGHT)
        
        """
        topFrame decoreren
        """
        #Scrolledtext in leftTopFrame
        self.scrDebug = ScrolledText(leftTopFrame, wrap = WORD, state = "disabled", fg = "green", width=65)
        self.scrDebug.pack(fill=NONE, expand=False)
        
        #Tekst in rightTopFrame
        self.lblLaatstGenomen = Label(rightTopFrame, text="Laatst genomen foto:", bg = "gray55", fg = "white")
        self.lblLaatstGenomen.pack()
        #Image in rightTopFrame
        self.location = "../latestPicture.gif"
        self.laatstGenomen = PhotoImage(file="../default.gif")
        self.lblFotoLaatstGenomen = Label(rightTopFrame, image=self.laatstGenomen)
        #self.lblFotoLaatstGenomen.image = self.laatstGenomen
        self.lblFotoLaatstGenomen.pack(fill = BOTH, expand = "yes")
        #Vertaling in rightTopFrame
        self.vertalingString = StringVar()
        self.vertalingString.set("Vertaling QR-code: ")
        self.lblVertaling = Label(rightTopFrame, textvariable = self.vertalingString, bg = "gray55", fg = "white")
        self.lblVertaling.pack()
        self.btnMaakFoto = Button(rightTopFrame, text = "Maak Foto", bg = "green", fg = "white", activebackground = "orange red", activeforeground = "white", width = 14, command = self.makePicture)
        self.btnMaakFoto.pack()
        #motor info in middleTopFrame
        self.lblmotorUpString = Label(middleTopFrame, text = "MOTOR U: " , bg = "blue", fg = "red", font = labelFont)
        self.lblmotorUpString.grid(row = 0, column = 0)
        self.lblmotorLeftString = Label(middleTopFrame, text = "MOTOR L: " , bg = "blue", fg = "red", font = labelFont)
        self.lblmotorLeftString.grid(row = 1, column = 0)
        self.lblmotorRightString = Label(middleTopFrame, text = "MOTOR R: " , bg = "blue", fg = "red", font = labelFont)
        self.lblmotorRightString.grid(row = 2, column = 0)
        self.lblmotorPWMString = Label(middleTopFrame, text = "PWM U: " , bg = "blue", fg = "white", font = labelFont)
        self.lblmotorPWMString.grid(row = 3, column = 0)
        self.motorLeftString = StringVar()
        self.motorLeftString.set("S")
        self.motorRightString = StringVar()
        self.motorRightString.set("S")
        self.motorUpString = StringVar()
        self.motorUpString.set("S")
        self.motorPWMString = StringVar()
        self.motorPWMString.set("100")
        self.lblmotorUpStringValue = Label(middleTopFrame, textvariable = self.motorUpString, fg = "red", bg = "blue", width = 5, font = labelFont)
        self.lblmotorUpStringValue.grid(row = 0, column = 1)
        self.lblmotorLeftStringValue = Label(middleTopFrame, textvariable = self.motorLeftString, fg = "red", bg = "blue", width = 5, font = labelFont)
        self.lblmotorLeftStringValue.grid(row = 1, column = 1)
        self.lblmotorRightStringValue = Label(middleTopFrame, textvariable = self.motorRightString, fg = "red", bg = "blue", width = 5, font = labelFont)
        self.lblmotorRightStringValue.grid(row = 2, column = 1)
        self.motorPWMStringValue = Label(middleTopFrame, textvariable = self.motorPWMString, fg = "white", bg = "blue", width = 5, font = labelFont)
        self.motorPWMStringValue.grid(row = 3, column = 1)
        """
        bottomFrame decoreren
        to do: enum
        """
        #Besturingsknoppen draaien in leftBottomFrame
        self.btnLeft = Button(leftBottomFrame, text="Links", bg = "green", fg = "white", activebackground = "orange red", activeforeground = "white", height=3, width=10, command = lambda: self.moveLeft())
        self.btnLeft.grid(row=1, column=0)
        self.btnRight = Button(leftBottomFrame, text="Rechts", bg = "green", fg = "white", activebackground = "orange red", activeforeground = "white", height=3, width=10, command = lambda: self.moveRight())
        self.btnRight.grid(row=1, column=2)
        self.btnForward = Button(leftBottomFrame, text="Vooruit", bg = "green", fg = "white", activebackground = "orange red", activeforeground = "white", height=3, width=10, command = lambda: self.moveForward())
        self.btnForward.grid(row=0, column=1)
        self.btnBackward = Button(leftBottomFrame, text="Achteruit", bg = "green", fg = "white", activebackground = "orange red", activeforeground = "white", height=3, width=10, command = lambda: self.moveBackward())
        self.btnBackward.grid(row=1, column=1)

        #Besturingsknoppen stijgen en dalen in middleBottomFrame
        self.btnUp = Button(leftRightBottomFrame, text="Omhoog", bg = "green", fg = "white", activebackground = "orange red", activeforeground = "white", height=3, width=10, command = lambda: self.moveUp())
        self.btnUp.grid(row=0, column=0)
        self.btnDown = Button(leftRightBottomFrame, text="Omlaag", bg = "green", fg = "white", activebackground = "orange red", activeforeground = "white", height=3, width=10, command = lambda: self.moveDown())
        self.btnDown.grid(row=1, column=0)
        
        self.lastCommandoString = ""
        
        #Hoogte informatie in RightBottomFrame
        self.gewensteHoogteString = StringVar()
        self.gewensteHoogteString.set(str(neededHeight))
        self.lblGewensteHoogte = Label(rightRightBottomFrame, text = "Gewenste Hoogte: ", anchor = "w", bg = "gray55", fg = "white")
        self.lblGewensteHoogteVar = Label(rightRightBottomFrame, textvariable = self.gewensteHoogteString, width = 20, fg = "green")      
        self.gemetenHoogteString = StringVar()
        self.gemetenHoogteString.set(str(realHeight))
        self.lblGemetenHoogte = Label(rightRightBottomFrame, text="Gemeten Hoogte:  ", anchor = "w", bg = "gray55", fg = "white")
        self.lblGemetenHoogteVar = Label(rightRightBottomFrame, textvariable = self.gemetenHoogteString, width = 20, fg = "green")
        self.lblGewensteHoogte.grid(row=1, column=0)
        self.lblGewensteHoogteVar.grid(row=1, column=1)
        self.lblGemetenHoogte.grid(row=0, column=0)
        self.lblGemetenHoogteVar.grid(row=0, column=1)
        self.btnHeight = Button(rightRightBottomFrame, text="Kies hoogte", bg = "green", fg = "white", activebackground = "orange red", activeforeground = "white", width = 14, command = lambda: self.setGewensteHoogte())
        self.btnHeight.grid(row=2,column=0)
        self.txtHeight = Entry(rightRightBottomFrame, width=24, fg = "green")
        self.txtHeight.grid(row=2, column=1)
        self.txtHeight.bind('<Return>', self.setGewensteHoogte)
        self.btnPWM = Button(rightRightBottomFrame, text="Kies PWM", bg = "green", fg = "white", activebackground = "orange red", activeforeground = "white", width = 14, command = lambda: self.setPWM())
        self.btnPWM.grid(row=2,column=2)
        self.txtPWM = Entry(rightRightBottomFrame, width = 24, fg = "green")
        self.txtPWM.grid(row=2, column = 3)
        self.txtPWM.bind('<Return>', self.setPWM)
        self.btnLand = Button(rightRightBottomFrame, text = "Landen", bg = "green", fg = "white", activebackground = "orange red", activeforeground = "white", width = 14, command = self.landen)
        self.btnLand.grid(pady=5,row=3, column = 0)
        self.btnHorizontalOff = Button(rightRightBottomFrame, text = "Horizontale motors af", bg = "green", fg = "white", activebackground = "orange red", activeforeground = "white", command = self.horizontalOff)
        self.btnHorizontalOff.grid(pady=5,row=3, column = 1)
        self.correctieFlag = False
        self.automaticFlag = False
        self.btnAutomaticPilot = Button(rightRightBottomFrame, text = "Auto-pilot", bg = "green", fg = "white",activebackground = "orange red", activeforeground = "white", width = 14, command = lambda: self.toggleAutomaticPilot())
        self.btnAutomaticPilot.grid(row = 0, column = 2)
        self.btnCorrectie = Button(rightRightBottomFrame, text ="Hoogte correctie", bg ="green", fg ="white", activebackground = "orange red", activeforeground = "white", width = 14, command = lambda: self.toggleHeightCorrection())
        self.btnCorrectie.grid(row = 1, column = 2)
        self.btnConnect = Button(rightRightBottomFrame, text = "Verbind", bg = "green", fg = "white", activebackground = "orange red", width = 14, activeforeground = "white", command = lambda: self.createClient())
        self.btnConnect.grid(row = 3, column = 2)
        self.connectedString = StringVar()
        self.connectedString.set("Niet verbonden")
        self.lblConnected = Label(rightRightBottomFrame, textvariable = self.connectedString, fg = "red", bg = "blue", font = tkFont.Font(size = 14))
        self.lblConnected.grid(row = 3, column = 3)
        self.createClient()
    
    #gewenste hoogte aanpassen    
    def setGewensteHoogte(self, event = None):
        x = self.txtHeight.get()
        self.txtHeight.delete(0, END)
        self.master.focus()
        try:
            x = float(x)
        except:
            return
        if isinstance(x, float) and x > 0.0 and x < 1000.0:
            global neededHeight
            neededHeight = x
            message = "Hoogte instellen op " + str(neededHeight) + " aangevraagd"
            self.debugPrint(message)
            self.gewensteHoogteString.set(str(neededHeight))
            self.client.setHeight(x)
            if not self.correctieFlag:
                self.toggleHeightCorrection()
                
    def toggleAutomaticPilot(self):
        if not self.connected:
            return
        self.debugPrint("Automatische piloot toggle aangevraagd")
        self.client.toggleAutomaticPilot()
        
                
    def createClient(self):
        try:
            self.client = cl(self)
            self.connected = True
            self.connectedString.set("Verbonden")
            self.lblConnected.config(fg = "green")
            self.debugPrint("Verbonden met Raspberry Pi")
        except:
            self.debugPrint("Verbinding met Rapsberry Pi niet mogelijk:\n    -Staat de Raspberry Pi aan?\n    -Staat de server aan?\n    -Zit deze computer op de ad-hoc?")
        
            
    def disconnect(self):
        self.connected = False
        self.connectedString.set("Niet verbonden")
        self.lblConnected.config(fg = "red")
                
    #PWM aanpassen  
    def setPWM(self, event = None):
        x = self.txtPWM.get()
        self.txtPWM.delete(0, END)
        self.master.focus()
        try:
            x = int(x)
        except:
            return
        try:
            if not self.connected:
                return
            message = "PWM instellen op " + str(x) + " aangevraagd"
            self.debugPrint(message)
            self.client.setPower(x)
        except TypeError:
            return
            
    #automatische hooogte correctie toggelen
    def toggleHeightCorrection(self):
        if not self.connected or self.automaticFlag:
            return
        self.debugPrint("Automatische hoogte regeling toggle aangevraagd")
        self.client.toggleHeightCorrection()
   
#     #make picture        
#     def makePicture(self):
#         if not self.connected:
#             return
#         decodation = self.client.fetchImage(self.location)
#         self.laatstGenomen2 = PhotoImage(file=self.location)
#         self.lblFotoLaatstGenomen.configure(image = self.laatstGenomen2)
#         self.vertalingString.set("VERTALING: " + str(decodation))

        #make picture        
    def makePicture(self):
        if not self.connected:
            return
        decodation = self.client.fetchImage("latestPicture.jpg")

    #tekst weergeven in debug venster    
    def debugPrint(self, tekst):
        self.scrDebug.config(state = "normal")
        self.scrDebug.insert(END, ">> " + tekst + "\n")
        self.scrDebug.config(state = "disabled")
        self.scrDebug.yview_pickplace("end")
        
    def moveForward(self):
        if not self.connected or self.automaticFlag:
            return
        self.debugPrint("Voorwaarts vliegen aangevraagd")
        self.client.flyForward()
        
    def moveBackward(self):
        if not self.connected or self.automaticFlag:
            return
        self.debugPrint("Achterwaarts vliegen aangevraagd")
        self.client.flyBackward()
    
    def moveLeft(self):
        if not self.connected or self.automaticFlag:
            return
        self.debugPrint("Links draaien aangevraagd")
        self.client.turnLeft()
        
    def moveRight(self):
        if not self.connected or self.automaticFlag:
            return
        self.debugPrint("Rechts draaien aangevraagd")
        self.client.turnRight()
        
    def moveUp(self):
        if not self.connected or self.automaticFlag:
            return
        self.debugPrint("Omhoog vliegen aangevraagd")
        if(self.correctieFlag):
            self.toggleHeightCorrection()
        self.client.motorUpBackward()
        
    def moveDown(self):
        if not self.connected or self.automaticFlag:
            return
        self.debugPrint("Omlaag vliegen aangevraagd")
        if(self.correctieFlag):
            self.toggleHeightCorrection()
        self.client.motorUpForward()
        
    def landen(self):
        if not self.connected or self.automaticFlag:
            return
        self.debugPrint("Landen aangevraagd")
        self.client.stopAllMotors() 
        
    def horizontalOff(self):
        if not self.connected or self.automaticFlag:
            return
        self.debugPrint("Horizontale motors stoppen aangevraagd")
        self.client.stopHorizontalMotors()
        
    def verticalOff(self):
        if not self.connected or self.automaticFlag:
            return
        self.debugPrint("Verticale motor stoppen aangevraagd")
        self.client.motorUpStop()
    
    #toetsenbord invoer
    def keyPressed(self, event):
        k = event.keysym
        if k == 'Up':
            if not self.btnUpPressed:
                self.btnUpPressed = True
                self.btnForward.config(bg = "orange red")
                self.btnForward.invoke()
        elif k == 'Down':
            if not self.btnDownPressed:
                    self.btnDownPressed = True
                    self.btnBackward.config(bg = "orange red")
                    self.btnBackward.invoke()
        elif k == 'Left':
            if not self.btnLeftPressed:
                self.btnLeftPressed = True
                self.btnLeft.config(bg = "orange red")
                self.btnLeft.invoke()
        elif k == 'Right':
            if not self.btnRightPressed:
                self.btnRightPressed = True
                self.btnRight.config(bg = "orange red")
                self.btnRight.invoke()
        elif k == 'plus':
            if not self.btnPlusPressed:
                self.btnPlusPressed = True
                self.btnUp.config(bg = "orange red")
                self.btnUp.invoke()
        elif k == 'minus':
            if not self.btnMinusPressed:
                self.btnMinusPressed = True
                self.btnDown.config(bg = "orange red")
                self.btnDown.invoke()
            
    def keyReleased(self, event):
        k = event.keysym
        if k == 'Up':
            self.btnUpPressed = False
            self.btnForward.config(bg = "green")
            self.horizontalOff()
        elif k == 'Down':
            self.btnDownPressed = False
            self.btnBackward.config(bg = "green")
            self.horizontalOff()
        elif k == 'Left':
            self.btnLeftPressed = False
            self.btnLeft.config(bg = "green")
            self.horizontalOff()
        elif k == 'Right':
            self.btnRightPressed = False
            self.btnRight.config(bg = "green")
            self.horizontalOff()
        elif k == 'plus':
            self.btnPlusPressed = False
            self.btnUp.config(bg = "green")
            self.verticalOff()
            
        elif k == 'minus':
            self.btnMinusPressed = False
            self.btnDown.config(bg = "green")
            self.verticalOff()
            
    def updateAutomatic(self, info):
        if info[0]:
            if not info[1] == "":
                if not info[1] == self.lastCommandoString:
                    self.lastCommandoString = info[1]
                    self.debugPrint(info[1])
            self.vertalingString.set("VERTALING: " + info[2])
            with open(self.location, "wb") as handle:
                handle.write(info[3].data)
            self.laatstGenomen2 = PhotoImage(file=self.location)
            self.lblFotoLaatstGenomen.configure(image = self.laatstGenomen2)
              
    def updateInfo(self, info):
        global realHeight
        if info[0] != -1:
            self.gemetenHoogteString.set(str(info[0]))
            self.motorUpString.set(info[1])
            
        if info[1] == "V" or info[1] == "A":
            self.lblmotorUpString.config(fg = "green")
            self.lblmotorUpStringValue.config(fg = "green")
        else: 
            self.lblmotorUpString.config(fg = "red")
            self.lblmotorUpStringValue.config(fg = "red")
        
        self.motorLeftString.set(info[2])
        if info[2] == "V" or info[2] == "A":
            self.lblmotorLeftString.config(fg = "green")
            self.lblmotorLeftStringValue.config(fg = "green")
        else: 
            self.lblmotorLeftString.config(fg = "red")
            self.lblmotorLeftStringValue.config(fg = "red")
        
        self.motorRightString.set(info[3])
        if info[3] == "V" or info[3] == "A":
            self.lblmotorRightString.config(fg = "green")
            self.lblmotorRightStringValue.config(fg = "green")
        else: 
            self.lblmotorRightString.config(fg = "red")
            self.lblmotorRightStringValue.config(fg = "red")
        
        self.motorPWMString.set(str(math.ceil(info[4])))
        self.correctieFlag = info[5]
        if(not self.correctieFlag):
            self.btnCorrectie.config(bg = "green")
        else:
            self.btnCorrectie.config(bg = "dark green")
            
        self.automaticFlag = info[6]
        if(not self.automaticFlag):
            self.btnAutomaticPilot.config(bg = "green")
        else:
            self.btnAutomaticPilot.config(bg = "dark green")
Example #5
0
class EvalGUI:    
    def __init__(self, master):
        master.title("Eval")
      
        self.master = master
        self.frame = Frame(master)
        self.frame.pack(fill=BOTH, expand=1)

        self.fixed_width_font = ("Courier New", -12)
        self.frame.columnconfigure(0, weight=1)
        
        self.eval = Eval()

        # output control
        row = 0        
        self.out = ScrolledText(self.frame, wrap=NONE, bd=0, width=80, height=25, undo=1, maxundo=50, padx=5, pady=5, font=self.fixed_width_font)
        self.out.grid(row=row, column=0, sticky="NEWS")
        self.frame.rowconfigure(row, weight=1)

        # input control
        row += 1        
        self.commandEntry = EvalGUI.ExpressionEntry(self, master=self.frame, font=self.fixed_width_font)
        self.commandEntry.grid(row=row, column=0, sticky=EW)
        self.commandEntry.focus_set()
        
    def calculate(self, command):                
        result = self.eval.calculate(command)
        if result.isError(): return result
        self.out.insert(END, "a[%d] = %s = %s\n" % (result.index, command, result.data))
        self.out.yview_pickplace(END)        
        return result

    class ExpressionEntry(Entry):
        def __init__(self, eval, **args):
            self.evalInst = eval
            Entry.__init__(self, **args)
            self.history = []
            self.historyIdx = 1
            self.history0Text = ""
            self.bind('<Return>', self.onEnter)
            self.bind('<Up>', self.onUp)
            self.bind('<Down>', self.onDown)            
        
        def set(self, text):
            self.delete(0, len(self.get()))
            self.insert(0, text)
            self.select_range(0, len(text))
        
        def onEnter(self, event):
            command = self.get()
            self.history.append(command)
            result = self.evalInst.calculate(command)
            if not result.isError():
                self.select_range(0, len(command))
            else:
                result.printError()
                self.set(result.getErrorString())
            self.historyIdx = 1
        
        def onUp(self, event):
            self.setHistory(1)

        def onDown(self, event):
            self.setHistory(-1)

        def setHistory(self, change):
            if len(self.history) == 0: return
            # check if current content corresponds to history index, otherwise reset
            if self.get() != self.history[-self.historyIdx]:
                self.historyIdx = 0
            # remember user entry before using history
            if self.historyIdx == 0:
                self.history0Text = self.get()
            # set new history index
            self.historyIdx += change
            # check bounds
            if self.historyIdx < 0:
                self.historyIdx = 0
            elif self.historyIdx > len(self.history):
                self.historyIdx = len(self.history)
            # set new content
            if self.historyIdx == 0:
                self.set(self.history0Text)            
            else:
                self.set(self.history[-self.historyIdx])