Example #1
0
 def test_move(self):
     for size in screen_sizes:
         with Display(visible=VISIBLE, size=size):
             mouse = PyMouse()
             for p in positions:
                 mouse.move(*p)
                 eq_(expect_pos(p, size), mouse.position())
Example #2
0
def click(pos):
    '''
    pos: (x, y) # (0, 0) for top left piece
    '''
    m = PyMouse()
    m.click(RECT[0] + PIECE_X / 2 + PIECE_X * pos[0], RECT[1] + PIECE_Y / 2 + PIECE_Y * pos[1])
    time.sleep(0.5)
	def showMouseLoc(self):
		try:
			m = PyMouse() # make mouse object
			while(1):
				print m.position() # print the position
		except KeyboardInterrupt:
			pass
def move ():
    deadzone_x = 200
    deadzone_y = 200
    key_delay = 0.4
    
    mouse = PyMouse()
    
    PORT = "/dev/ttyACM1"
    #~ PORT = "/dev/serial/by-id/usb-MBED_MBED_CMSIS-DAP_9900023431864e45001210060000003700000000cc4d28bd-if01"
    BAUD = 115200
    
    s = serial.Serial(PORT)
    s.baudrate = BAUD
    s.parity = serial.PARITY_NONE
    s.databits = serial.EIGHTBITS
    s.stopbits = serial.STOPBITS_ONE
    
    while True:
        data = s.readline().decode('UTF-8')
        data_list = data.rstrip().split(' ')
        try:
            x, y, z, a, b = data_list
            x_mapped = arduino_map(int(x), -1024, 1024, -960, 960)
            y_mapped = arduino_map(int(y), -1024, 1024, -540, 540)
            
            x_centre = 960
            y_centre = 540
        
            print(x_mapped, y_mapped)
            mouse.move(x_centre + x_mapped, y_centre + y_mapped)
        
        except:
            pass
        
    s.close()
Example #5
0
def move_down():
    m = PyMouse()
    xt=random.randint(1400, 1600)
    yt=random.randint(700, 800)

    m.position()
    m.move(xt, yt)
    def draw_arc(self, window):
        #self.drawing_area.window.draw_arc(self.context, False, self._x, self._y, 70, 70, 0, 360*64)
	window.set_keep_below(True)
	window.hide()
	m = PyMouse()
	m.move(self._x, self._y)
	m.click(self._x, self._y, 1)
def mouse_simulate():
    try:
        class event(PyMouseEvent):
            def move(self, x, y):
                pass

            def click(self, x, y, button, press):
                if press:
                    print("Mouse pressed at", x, y, "with button", button)
                else:
                    print("Mouse released at", x, y, "with button", button)
        e = event()
        e.start()

    except ImportError:
        print("Mouse events are not yet supported on your platform")

    m = PyMouse()

    t_corr = (1173,313)
    i_pos = t_corr
    m.move(i_pos[0] , i_pos[1])

    while(True):
        if is_run is False:
            time.sleep(1)
        else:
            time.sleep(0.2)
            m.click(i_pos[0], i_pos[1])

    try:
        e.stop()
    except:
        pass
class Mouse:
    def __init__(self):
        import autopy
        from pymouse import PyMouse

        self.m1 = autopy.mouse
        self.loc = [self.m1.get_pos()[0],self.m1.get_pos()[1]]
        self.m = PyMouse()
        self.m.move(self.loc[0], self.loc[1])

    def move(self,direction):
        #Move mouse
        self.loc[0] += direction[0]
        self.loc[1] += direction[1]
        #FIXME: Support multiple displays
        #Check horizontal bounds
        self.loc[0] = min(self.loc[0],3600)#self.m.screen_size()[0])
        self.loc[0] = max(self.loc[0],0)
        #Check vertical bounds
        self.loc[1] = min(self.loc[1],self.m.screen_size()[1])
        self.loc[1] = max(self.loc[1],0)
        self.m.move(int(self.loc[0]), int(self.loc[1]))

    def click(self,button):
        self.m1.click(button)
Example #9
0
def main():
    mouse = PyMouse()

    # 	wm = cwiid.Wiimote("00:25:A0:CE:3B:6D")
    wm = cwiid.Wiimote()
    wm.rpt_mode = cwiid.RPT_BTN | cwiid.RPT_IR

    X, x = calibrate(wm)
    trans = getTransMatrix(x, X)

    screen = mouse.screen_size()
    lastTime = time.time()
    o = None

    state = NEUTRAL

    print("battery: %f%%" % (float(wm.state["battery"]) / float(cwiid.BATTERY_MAX) * 100.0))

    window = pygame.display.set_mode((200, 150))

    while True:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                sys.exit(0)

        pos = getWiiPointNonBlock(wm)

        if pos != None:
            ipt = numpy.matrix([[pos.x], [pos.y], [1]])
            optMat = trans.I * ipt
            o = Point(optMat[0] / optMat[2], optMat[1] / optMat[2])

            if o.x < 0:
                o.x = 0
            elif o.x >= screen[0]:
                o.x = screen[0] - 1

            if o.y < 0:
                o.y = 0
            elif o.y >= screen[1]:
                o.y = screen[1] - 1

            if state == NEUTRAL:
                state = FIRST_INPUT
                lastTime = time.time()
            elif state == FIRST_INPUT:
                if time.time() - FIRST_INPUT_TO_PRESSED > lastTime:
                    mouse.press(o.x, o.y)
                    state = PRESSED
            elif state == PRESSED:
                mouse.move(o.x, o.y)

        if state == FIRST_INPUT and pos == None and time.time() - FIRST_INPUT_TO_PRESSED < lastTime:
            mouse.click(o.x, o.y)
            time.sleep(0.2)
            state = NEUTRAL

        if state == PRESSED and pos == None and time.time() - 1 > lastTime:
            mouse.release(o.x, o.y)
            state = NEUTRAL
Example #10
0
    def run(self):
        global mself
        global runflag
        
        m = PyMouse()

        #raw_input("请先将鼠标移动到数据位置的左上角,然后按下回车.")
        wx.MessageBox("请不要点击该对话框的确定按钮\n先将鼠标移动到数据位置的左上角,然后按下回车...", "获取数据位置", wx.OK)
        p1 = m.position()
        print p1
        #raw_input("接下来将鼠标移动到数据位置的右下角,然后按下回车.")
        wx.MessageBox("接下来将鼠标移动到数据位置的右下角,然后按下回车...", "获取数据位置", wx.OK)
        p2 =  m.position()
        print p2
        print "完成数据位设定,开始获取数据工作."
        imbox = (p1[0], p1[1], p2[0], p2[1])

        prev_s = [0,0,0,0]
        while runflag:
            try:
                im = ImageGrab.grab(imbox)
                s = image_to_string(im)
                s = s.split()
                if s != prev_s and len(s)==4 :
                    sell =  float(s[0]) - float(prev_s[0])
                    buy = float(s[2]) - float(prev_s[2])
                    prev_s = s

                    print sell, buy
                    mself.staticText1.SetLabel(mself.staticText2.GetLabel())
                    mself.staticText2.SetLabel(mself.staticText3.GetLabel())
                    mself.staticText3.SetLabel(mself.staticText4.GetLabel())
                    mself.staticText4.SetLabel(mself.staticText5.GetLabel())
                    mself.staticText5.SetLabel(mself.staticText6.GetLabel())
                    mself.staticText6.SetLabel(mself.staticText7.GetLabel())
                    mself.staticText7.SetLabel(mself.staticText8.GetLabel())
                    mself.staticText8.SetLabel(mself.staticText9.GetLabel())
                    mself.staticText9.SetLabel(mself.staticText10.GetLabel())
                    mself.staticText10.SetLabel("%.1f"%sell)

                    mself.staticText11.SetLabel(mself.staticText12.GetLabel())
                    mself.staticText12.SetLabel(mself.staticText13.GetLabel())
                    mself.staticText13.SetLabel(mself.staticText14.GetLabel())
                    mself.staticText14.SetLabel(mself.staticText15.GetLabel())
                    mself.staticText15.SetLabel(mself.staticText16.GetLabel())
                    mself.staticText16.SetLabel(mself.staticText17.GetLabel())
                    mself.staticText17.SetLabel(mself.staticText18.GetLabel())
                    mself.staticText18.SetLabel(mself.staticText19.GetLabel())
                    mself.staticText19.SetLabel(mself.staticText20.GetLabel())
                    mself.staticText20.SetLabel("%.1f"%buy)

                im.save("show.jpg")
                pic=wx.Image("show.jpg")
                w,h = mself.staticBitmap1.GetSize()
                mself.staticBitmap1.SetBitmap(pic.Rescale(w,h).ConvertToBitmap())
            except:
                traceback.print_exc()
                wx.MessageBox("无法正常识别,请重新开始.注意数据截取位置.", "提醒", wx.OK)
                runflag = 0
Example #11
0
 def test_move(self):
     for size in screen_sizes:
         with Display(visible=VISIBLE, size=size) as d:
             time.sleep(0.5)
             mouse = PyMouse(display=d.new_display_var)
             for p in positions:
                 mouse.move(*p)
                 eq_(expect_pos(p, size), mouse.position())
	def ut_showMouseLoc(self):
		points = [(120,120), (600,480), (500,1000), (800,200)]
		m = PyMouse() # make mouse object
		for point in points:
			print "Moving to: ", point
			m.move(point[0],point[1])
			print "The Mouse is at:", m.position()
		print "Test complete!"	
Example #13
0
 def test_size(self):
     for size in screen_sizes:
         try:
             disp = Display(visible=VISIBLE, size=size).start()
             mouse = PyMouse()
             eq_(size, mouse.screen_size())
         finally:
             disp.stop()
Example #14
0
    def on_message(self, message):
        m = PyMouse()
        data = json.loads(message)
        source = data['from']
        destination = data['to']
        offset = data['offset']

        m.click(source['x'] + offset, source['y'] + offset)
        m.click(destination['x'] + offset, destination['y'] + offset)
Example #15
0
def click(p, t = 0.6):
    x = p.x
    y = p.y
    m = PyMouse()
    m.move(x, y)
    m.click(x, y, 1)
#    m.press(x, y)
#    m.release(x, y)
    time.sleep(t)
Example #16
0
def listen_mouse():
    m = PyMouse()
    while 1:
        data = sock.recv(16)
        _pos = data
        _x = _pos.split('(')[1].split(',')[0]
        _y = _pos.split(' ')[1].split(')')[0]
        m.move(int(_x), int(_y))
        sleep(0.1)
Example #17
0
def wheel(ticks):
    """
    Simulates a mouse wheel movement

    Args:
        ticks (int) : number of increments to scroll the wheel
    """
    m = PyMouse()
    m.scroll(ticks)
Example #18
0
 def test_move(self):
     for size in screen_sizes:
         try:
             disp = Display(visible=VISIBLE, size=size).start()
             mouse = PyMouse()
             for p in positions:
                 mouse.move(*p)
                 eq_(expect_pos(p, size), mouse.position())
         finally:
             disp.stop()
Example #19
0
def zoom_out():
    m = PyMouse()
    (x, y) = m.position()
    m.move(700, 700)
    press()
    # m.move(200, 100)
    # m.move(300, 100)
    # m.move(400, 100)
    # m.move(500, 100)
    release()
Example #20
0
def all_in(a=None):
    m = PyMouse()
    if a:
        time.sleep(a)
    k = (679,558)
    m.click(k[0],k[1], 1)
    for a in range(0,13):
        wsh.SendKeys("9")
    wsh.SendKeys("{ENTER} ")
    wsh.SendKeys("{F3}")
Example #21
0
def move(point):
    """
    Moves the mouse cursor to the provided location

    Args:
        point (int, int): location (x,y) of the screen to place the cursor
    """
    # wrapper just so we don't have to import pymouse separately
    m = PyMouse()
    m.move(*point)
Example #22
0
class Robot(object):

    def __init__(self):
        self.mouse = PyMouse()
        self.keyboard = PyKeyboard()
        self.przyciskPSP2klawiatura = {'up': 'w', 'right': 'd', 'down': 's', 'left': 'a', 'triangle': self.keyboard.enter_key,
                                       'circle': 'f', 'cross': 'g', 'square': 'h', 'l': self.keyboard.control_r_key, 'r': self.keyboard.shift_r_key, 'start': 'k', 'select': 'l'}

    def reaguj(self, x, y, przyciskPSP2Stan):
        self.reaguj_mysz(x, y)
        self.reaguj_klawiatura(przyciskPSP2Stan)

    def reaguj_mysz(self, x, y):
        max_predkosc_kursora = 0.00000000000000000000000000000000000000000000000000001
        x += int((x / float(128)) * max_predkosc_kursora +
                 self.mouse.position()[0])
        y += int((y / float(128)) * max_predkosc_kursora +
                 self.mouse.position()[1])
        x, y = min(self.mouse.screen_size()[0], x), min(
            self.mouse.screen_size()[1], y)
        x, y = max(0, x), max(0, y)
        self.mouse.move(x, y)

    def reaguj_klawiatura(self, przyciskPSP2Stan):
        for przycisk_psp, czyWcisniety in przyciskPSP2Stan.iteritems():
            przycisk_klawiaturowy = self.przyciskPSP2klawiatura[przycisk_psp]
            if czyWcisniety == '1':
                if przycisk_klawiaturowy == 'g':
                    self.mouse.click(*self.mouse.position())
                    break
                self.keyboard.press_key(przycisk_klawiaturowy)
            else:
                self.keyboard.release_key(przycisk_klawiaturowy)
Example #23
0
 def test_1st_event(self):
     size = (100, 100)
     try:
         disp = Display(visible=VISIBLE, size=size).start()
         mouse = PyMouse()
         event = Event()
         event.start()
         event.pos = None
         mouse.move(10, 10)
         time.sleep(0.1)
         eq_((10, 10), event.pos)
         event.stop()                
     finally:
         disp.stop()
Example #24
0
 def test_event(self):
     for size in screen_sizes:
         try:
             disp = Display(visible=VISIBLE, size=size).start()
             mouse = PyMouse()
             event = Event()
             event.start()
             for p in positions:
                 event.pos = None
                 mouse.move(*p)
                 eq_(expect_pos(p, size), event.pos)
             event.stop()                
         finally:
             disp.stop()
Example #25
0
class WinMouseControl():
    
    mouseObject=''
    def __init__(self):
        self.mouseObject=PyMouse()
        print "mouse init success"
        pass
    
    def __del__(self):
        pass
    
    def mouseMove(self,x,y,button=None):
        self.mouseObject.move(x, y)
        return 0
    
    def mouseClick(self,x,y,button):
        self.mouseObject.click(x, y, button)   #button:1 left, button2: middle button3:right
        return 0
    
    def mousePress(self,x,y,button):
        self.mouseObject.press(x, y, button)   #button:1 left, button2: middle button3:right
        return 0
    
    def mouseRelease(self,x,y,button):
        self.mouseObject.release(x, y, button)   #button:1 left, button2: middle button3:right
        return 0
    def mousePressEvent (self, event):
        if event.button() == QtCore.Qt.LeftButton:
            self.parent.hide()
            pos=event.pos()
            mouse = PyMouse()
            
            time.sleep(0.2)
            mouse.click(pos.x(), pos.y())

            # parent is PositionSelectionUI
            self.parent.callTimerAndRun()
            self.parent.timer_window.move(pos.x() + 320, pos.y() - 380)

        QtGui.QWidget.mousePressEvent(self, event)
Example #27
0
    def flicker(self):
        """
        This method simply jiggles the mouse. It is used as
        part of a workaround for LoopingCall's getting stuck
        on the first call when using qt4reactor on linux.
        """
        from platform import system

        if (self.activeWindow is not None) and system() == "Linux":
            from pymouse import PyMouse

            m = PyMouse()
            x, y = m.position()
            m.move(x + 1, y)
Example #28
0
def reg(nu,name,call):
    m = PyMouse()
    poz = m.position()
    #dealer##box = (poz[0] -15,poz[1]-5,poz[0]+15,poz[1]+5)
    box = (poz[0] -35,poz[1]-15,poz[0]+35,poz[1]+15)   
    got = False
    for t in call:
        if t[0] == nu:
            t[1].append([nu+name+'.png',box])
            got = True
            break
    if not got:
        call.append([nu,[[nu+name+'.png',box]]])
    ImageGrab.grab(bbox=box).save('add/%s'%(nu+name+'.png'),'BMP')
Example #29
0
 def test_event(self):
     for size in screen_sizes:
         with Display(visible=VISIBLE, size=size):
             time.sleep(3)  # TODO: how long should we wait?
             mouse = PyMouse()
             event = Event()
             event.start()
             for p in positions:
                 event.pos = None
                 mouse.move(*p)
                 time.sleep(0.1)  # TODO: how long should we wait?
                 print 'check ', expect_pos(p, size), '=', event.pos
                 eq_(expect_pos(p, size), event.pos)
             event.stop()                
Example #30
0
    def initializeParameters(self):

        with open('./.pathToAP', 'r') as textFile:
            self.pathToAP = textFile.readline()

        sys.path.append(self.pathToAP)
        from reader import reader

        self.reader = reader()
        self.reader.readParameters()
        parameters = self.reader.getParameters()
        self.unpackParameters(parameters)

        self.flag = 'row'
        self.pressFlag = False
        self.pressedStopFlag = False

        self.rowIteration = 0
        self.colIteration = 0

        self.rowIteration = 0
        self.colIteration = 0

        self.numberOfColumns = 2,
        self.numberOfRows = 5,

        self.numberOfSymbol = 0

        self.numberOfEmptyIteration = 0
        self.countRows = 0
        self.countColumns = 0
        self.button = 1
        self.countMaxRows = 2
        self.countMaxColumns = 2
        self.numberOfPresses = 0

        self.volumeLevels = [0, 20, 40, 60, 80, 100, 120, 140, 160]
        if self.volumeLevel not in self.volumeLevels:
            raise (
                "Wrong value of volumeLevel. Accepted values: 0, 20, 40, 60, 80, 100, 120, 140, 160"
            )

        ### if download option was available
    # self.youtubeFiles = sorted( glob.glob('./youtube playlist/*') )
    # if bool( self.youtubeFiles ) == False:
    #         self.lastYoutubeFile = 1
    # else:
    #         self.lastYoutubeFile = self.youtubeFiles[-1]

        if self.control != 'tracker':
            self.mouseCursor = PyMouse()
            # self.mousePosition = self.winWidth - 8 - self.xBorder, self.winHeight - 16 - self.yBorder
            # self.mouseCursor.move( *self.mousePosition )
            self.mouseCursor.move(self.dw - 225, self.dh - 265)

        if self.switchSound.lower() != 'off' or self.pressSound.lower(
        ) != 'off':
            mixer.init()
            self.switchingSound = mixer.Sound(self.pathToAP +
                                              '/sounds/switchSound.ogg')
            self.pressingSound = mixer.Sound(self.pathToAP +
                                             '/sounds/pressSound.ogg')

            self.ciszejSound = mixer.Sound(self.pathToAP +
                                           '/sounds/ciszej.ogg')
            self.glosniejSound = mixer.Sound(self.pathToAP +
                                             '/sounds/glosniej.ogg')

            self.nastepnySound = mixer.Sound(self.pathToAP +
                                             '/sounds/następny.ogg')
            self.poprzedniSound = mixer.Sound(self.pathToAP +
                                              '/sounds/poprzedni.ogg')

            self.zatrzymajGrajSound = mixer.Sound(self.pathToAP +
                                                  '/sounds/zatrzymaj_graj.ogg')
            self.pelnyEkranSound = mixer.Sound(self.pathToAP +
                                               '/sounds/pełny_ekran.ogg')

            self.wyjscieSound = mixer.Sound(self.pathToAP +
                                            '/sounds/wyjście.ogg')
            self.powrotSound = mixer.Sound(self.pathToAP +
                                           '/sounds/powrot.ogg')
            self.usypiamSound = mixer.Sound(self.pathToAP +
                                            '/sounds/usypiam.ogg')

            self.oneSound = mixer.Sound(self.pathToAP + '/sounds/rows/1.ogg')
            self.twoSound = mixer.Sound(self.pathToAP + '/sounds/rows/2.ogg')
            self.threeSound = mixer.Sound(self.pathToAP + '/sounds/rows/3.ogg')
            self.fourSound = mixer.Sound(self.pathToAP + '/sounds/rows/4.ogg')
            self.fiveSound = mixer.Sound(self.pathToAP + '/sounds/rows/5.ogg')

        self.width = self.numberOfColumns[0] * 120
        self.height = self.numberOfRows[0] * 100
Example #31
0
class speller( wx.Frame ):
	def __init__(self, parent, id):

		self.winWidth, self.winHeight = wx.DisplaySize( )

		wx.Frame.__init__( self , parent , id , 'ATPlatform Speller' )
		style = self.GetWindowStyle( )
		self.SetWindowStyle( style | wx.STAY_ON_TOP )
		self.parent = parent

		self.Maximize( True )
		self.Centre( True )
		self.MakeModal( True )

		self.initializeParameters( )
		self.initializeBitmaps( )
		self.createGui( )
		self.initializeTimer( )
		self.createBindings( )

	#-------------------------------------------------------------------------
	def initializeParameters(self):
                
            with open( './.pathToATPlatform' ,'r' ) as textFile:
		    self.pathToATPlatform = textFile.readline( )
		    
	    with open( self.pathToATPlatform + 'parameters', 'r' ) as parametersFile:
		    for line in parametersFile:

			    if line[ :line.find('=')-1 ] == 'timeGap':
				    self.timeGap = int( line[ line.rfind('=')+2:-1 ] )
			    elif line[ :line.find('=')-1 ] == 'backgroundColour':
				    self.backgroundColour = line[ line.rfind('=')+2:-1 ]
			    elif line[ :line.find('=')-1 ] == 'textColour':
				    self.textColour = line[ line.rfind('=')+2:-1 ]
			    elif line[ :line.find('=')-1 ] == 'scanningColour':
				    self.scanningColour = line[ line.rfind('=')+2:-1 ]
			    elif line[ :line.find('=')-1 ] == 'selectionColour':
				    self.selectionColour = line[ line.rfind('=')+2:-1 ]
			    elif line[ :line.find('=')-1 ] == 'filmVolume':
				    self.filmVolumeLevel = int( line[ line.rfind('=')+2:-1 ] )
			    elif line[ :line.find('=')-1 ] == 'musicVolume':
			    	    self.musicVolumeLevel = int( line[ line.rfind('=')+2:-1 ] )
			
			    elif not line.isspace( ):
				    print 'Niewłaściwie opisane parametry'
				    print 'Błąd w pliku parameters w linii', line
				    
				    self.timeGap = 1500
				    self.backgroundColour = 'white'
				    self.textColour = 'black'
				    self.scanningColour =  '#E7FAFD'
				    self.selectionColour = '#9EE4EF'
				    self.filmVolumeLevel = 100
				    self.musicVolumeLevel = 40

	    with open( self.pathToATPlatform + 'spellerParameters', 'r' ) as parametersFile:
		    for line in parametersFile:

			    if line[ :line.find('=')-1 ] == 'voice':
				    self.voice = line[ line.rfind('=')+2:-1 ]
			    elif line[ :line.find('=')-1 ] == 'vowelColour':
				    self.vowelColour = line[ line.rfind('=')+2:-1 ]
			    elif line[ :line.find('=')-1 ] == 'polishLettersColour':
				    self.polishLettersColour = line[ line.rfind('=')+2:-1 ]
			
			    elif not line.isspace( ):
				    print 'Niewłaściwie opisane parametry'
				    print 'Błąd w pliku spellerParameters w linii', line
				    
				    self.voice = 'False'
				    self.vowelColour = 'False'
				    self.polishLettersColour = 'False'

	    self.labels = [ 'A E B C D F G H I O J K L M N P U Y R S T W Z SPECIAL_CHARACTERS UNDO SPEAK SAVE SPACJA OPEN EXIT'.split( ), '1 2 3 4 5 6 7 8 9 0 + - * / = % $ & . , ; : " ? ! @ # ( ) [ ] { } < > ~ UNDO SPEAK SAVE SPACJA OPEN EXIT'.split( ) ]
	    
	    self.colouredLabels = [ 'A', 'E', 'I', 'O', 'U', 'Y' ]

	    self.numberOfRows = [ 4, 5 ]
	    self.numberOfColumns = [ 8, 9 ]
				
	    self.flag = 'row'						
	    self.rowIteration = 0						
	    self.columnIteration = 0							
	    self.countRows = 0
	    self.countColumns = 0										

	    self.maxNumberOfRows = 2
	    self.maxNumberOfColumns = 2									
	    
	    self.numberOfPresses = 1
	    self.subSizerNumber = 0

	    self.mouseCursor = PyMouse( )
	    self.mousePosition = self.winWidth - 8, self.winHeight - 8
	    self.mouseCursor.move( *self.mousePosition )			

	    mixer.init( )
	    self.typewriterKeySound = mixer.Sound( self.pathToATPlatform + 'sounds/typewriter_key.wav' )
	    self.typewriterForwardSound = mixer.Sound( self.pathToATPlatform + 'sounds/typewriter_forward.wav' )
	    self.typewriterSpaceSound = mixer.Sound( self.pathToATPlatform + 'sounds/typewriter_space.wav' )

	    if self.voice == 'True':
		    self.phones = glob.glob( self.pathToATPlatform + 'sounds/phone/*' )
		    self.phoneLabels = [ item[ item.rfind( '/' )+1 : item.rfind( '.' ) ] for item in self.phones ]
		    self.sounds = [ mixer.Sound( self.sound ) for self.sound in self.phones ]
	    
	    self.SetBackgroundColour( 'black' )
		
	#-------------------------------------------------------------------------
        def initializeBitmaps(self):
            
            labelFiles = [ self.pathToATPlatform + file for file in [ 'icons/speller/special_characters.png', 'icons/speller/undo.png', 'icons/speller/speak.png', 'icons/speller/save.png', 'icons/speller/open.png', 'icons/speller/exit.png', ] ]
            
            self.labelBitmaps = { }
	    
	    labelBitmapIndex = [ self.labels[ 0 ].index( self.labels[ 0 ][ -7 ] ), self.labels[ 0 ].index( self.labels[ 0 ][ -6 ] ), self.labels[ 0 ].index( self.labels[ 0 ][ -5 ] ), self.labels[ 0 ].index( self.labels[ 0 ][ -4 ] ), self.labels[ 0 ].index( self.labels[ 0 ][ -2 ] ), self.labels[ 0 ].index( self.labels[ 0 ][ -1 ] ) ]

            for labelFilesIndex, labelIndex in enumerate( labelBitmapIndex ):
		    self.labelBitmaps[ self.labels[ 0 ][ labelIndex ] ] = wx.BitmapFromImage( wx.ImageFromStream( open( labelFiles[ labelFilesIndex ], 'rb' )) )      

            self.labelBitmaps2 = { }
	    
	    labelBitmapIndex2 = [ self.labels[ 1 ].index( self.labels[ 1 ][ -6 ] ), self.labels[ 1 ].index( self.labels[ 1 ][ -5 ] ), self.labels[ 1 ].index( self.labels[ 1 ][ -4 ] ), self.labels[ 1 ].index( self.labels[ 1 ][ -2 ] ), self.labels[ 1 ].index( self.labels[ 1 ][ -1 ] ) ]

            for labelFilesIndex2, labelIndex2 in enumerate( labelBitmapIndex2 ):
		    self.labelBitmaps2[ self.labels[ 1 ][ labelIndex2 ] ] = wx.BitmapFromImage( wx.ImageFromStream( open( labelFiles[ -5: ][ labelFilesIndex2 ], 'rb' )) )

	#-------------------------------------------------------------------------	
	def createGui(self):
		
		self.mainSizer = wx.BoxSizer( wx.VERTICAL )
		self.textField = wx.TextCtrl( self, style = wx.TE_LEFT, size = ( self.winWidth, 0.2 * self.winHeight ) )
		self.textField.SetFont( wx.Font( 60, wx.SWISS, wx.NORMAL, wx.NORMAL ) )
		self.mainSizer.Add( self.textField, flag = wx.EXPAND | wx.TOP | wx.BOTTOM, border = 3 )
		
		self.subSizers = [ ]
		
		subSizer = wx.GridBagSizer( 3, 3 )

		for index_1, item in enumerate( self.labels[ 0 ][ :-7 ] ):
			b = bt.GenButton( self, -1, item, name = item, size = ( 0.985*self.winWidth / self.numberOfColumns[ 0 ], 0.745 * self.winHeight / self.numberOfRows[ 0 ] ) )
			b.SetFont( wx.Font( 35, wx.FONTFAMILY_ROMAN, wx.FONTWEIGHT_LIGHT,  False ) )
			b.SetBezelWidth( 3 )
			b.SetBackgroundColour( self.backgroundColour )

			if item in self.colouredLabels and self.vowelColour != 'False':
				b.SetForegroundColour( self.vowelColour )
			else:
				b.SetForegroundColour( self.textColour )

			b.Bind( wx.EVT_LEFT_DOWN, self.onPress )
			subSizer.Add( b, ( index_1 / self.numberOfColumns[ 0 ], index_1 % self.numberOfColumns[ 0 ] ), wx.DefaultSpan, wx.EXPAND )

		for index_2, item in enumerate( self.labels[ 0 ][ -7 : -3 ], start = 1 ):
			b = bt.GenBitmapButton( self, -1, bitmap = self.labelBitmaps[ item ] )
			b.SetBackgroundColour( self.backgroundColour )
			b.SetBezelWidth( 3 )
                        b.Bind( wx.EVT_LEFT_DOWN, self.onPress )
			subSizer.Add( b, ( ( index_1 + index_2 ) / self.numberOfColumns[ 0 ], ( index_1 + index_2 ) % self.numberOfColumns[ 0 ] ), wx.DefaultSpan, wx.EXPAND )

		for item in ( self.labels[ 0 ][ -3 ], ):
			b = bt.GenButton( self, -1, item, name = item, size = ( 3 * 0.985*self.winWidth / self.numberOfColumns[ 0 ], 0.745 * self.winHeight / self.numberOfRows[ 0 ] ) )
			b.SetFont( wx.Font( 35, wx.FONTFAMILY_ROMAN, wx.FONTWEIGHT_LIGHT,  False ) )
			b.SetBezelWidth( 3 )
			b.SetBackgroundColour( self.backgroundColour )
			b.SetForegroundColour( self.textColour )
			b.Bind( wx.EVT_LEFT_DOWN, self.onPress )
			subSizer.Add( b, ( ( index_1 + index_2 ) / self.numberOfColumns[ 0 ], ( index_1 + index_2 + 1 ) % self.numberOfColumns[ 0 ] ), ( 1, 3 ), wx.EXPAND )

		for index_3, item in enumerate( self.labels[ 0 ][ -2: ], start = 4 ):
			b = bt.GenBitmapButton( self, -1, bitmap = self.labelBitmaps[ item ] )
			b.SetBackgroundColour( self.backgroundColour )
			b.SetBezelWidth( 3 )
                        b.Bind( wx.EVT_LEFT_DOWN, self.onPress )
			subSizer.Add( b, ( ( index_1 + index_2 + index_3 ) / self.numberOfColumns[ 0 ], ( index_1 + index_2 + index_3 ) % self.numberOfColumns[ 0 ] ), wx.DefaultSpan, wx.EXPAND )

		self.subSizers.append( subSizer )		    
		self.mainSizer.Add( self.subSizers[ 0 ], proportion = 1, flag = wx.EXPAND )
		self.SetSizer( self.mainSizer )
		self.Center( )
		
		subSizer2 = wx.GridBagSizer( 3, 3 )

		for index_1, item in enumerate( self.labels[ 1 ][ :-6 ] ):
			b = bt.GenButton( self, -1, item, name = item, size = ( 0.985*self.winWidth / self.numberOfColumns[ 1 ], 0.7 * self.winHeight / self.numberOfRows[ 1 ] ) )
			b.SetFont( wx.Font( 35, wx.FONTFAMILY_ROMAN, wx.FONTWEIGHT_LIGHT,  False ) )
			b.SetBezelWidth( 3 )
			b.SetBackgroundColour( self.backgroundColour )
			b.SetForegroundColour( self.textColour )
			b.Bind( wx.EVT_LEFT_DOWN, self.onPress )
			subSizer2.Add( b, ( index_1 / self.numberOfColumns[ 1 ], index_1 % self.numberOfColumns[ 1 ] ), wx.DefaultSpan, wx.EXPAND )

		for index_2, item in enumerate( self.labels[ 1 ][ -6 : -3 ], start = 1 ):
			b = bt.GenBitmapButton( self, -1, bitmap = self.labelBitmaps2[ item ] )
			b.SetBackgroundColour( self.backgroundColour )
			b.SetBezelWidth( 3 )
                        b.Bind( wx.EVT_LEFT_DOWN, self.onPress )
			subSizer2.Add( b, ( ( index_1 + index_2 ) / self.numberOfColumns[ 1 ], ( index_1 + index_2 ) % self.numberOfColumns[ 1 ] ), wx.DefaultSpan, wx.EXPAND )

		for item in ( self.labels[ 1 ][ -3 ], ):
			b = bt.GenButton( self, -1, item, name = item, size = ( 3 * 0.985*self.winWidth / self.numberOfColumns[ 1 ], 0.7 * self.winHeight / self.numberOfRows[ 1 ] ) )
			b.SetFont( wx.Font( 35, wx.FONTFAMILY_ROMAN, wx.FONTWEIGHT_LIGHT,  False ) )
			b.SetBezelWidth( 3 )
			b.SetBackgroundColour( self.backgroundColour )
			b.SetForegroundColour( self.textColour )
			b.Bind( wx.EVT_LEFT_DOWN, self.onPress )
			subSizer2.Add( b, ( ( index_1 + index_2 ) / self.numberOfColumns[ 1 ], ( index_1 + index_2 + 1 ) % self.numberOfColumns[ 1 ] ), ( 1, 4 ), wx.EXPAND )

		for index_3, item in enumerate( self.labels[ 1 ][ -2: ], start = 5 ):
			b = bt.GenBitmapButton( self, -1, bitmap = self.labelBitmaps2[ item ] )
			b.SetBackgroundColour( self.backgroundColour )
			b.SetBezelWidth( 3 )
                        b.Bind( wx.EVT_LEFT_DOWN, self.onPress )
			subSizer2.Add( b, ( ( index_1 + index_2 + index_3 ) / self.numberOfColumns[ 1 ], ( index_1 + index_2 + index_3 ) % self.numberOfColumns[ 1 ] ), wx.DefaultSpan, wx.EXPAND )

		self.subSizers.append( subSizer2 )		   
		self.mainSizer.Add( self.subSizers[ 1 ], proportion = 1, flag = wx.EXPAND )
		self.mainSizer.Show( item = self.subSizers[ 1 ], show = False, recursive = True )
		self.SetSizer( self.mainSizer )
		self.Center( )

	#-------------------------------------------------------------------------
	def initializeTimer(self):
		self.stoper = wx.Timer( self )
		self.Bind( wx.EVT_TIMER, self.timerUpdate, self.stoper )
		self.stoper.Start( self.timeGap )
	
	#-------------------------------------------------------------------------
	def createBindings(self):
		self.Bind( wx.EVT_CLOSE, self.OnCloseWindow )
	
	#-------------------------------------------------------------------------
	def OnCloseWindow(self, event):

		self.mousePosition = self.winWidth/1.85, self.winHeight/1.85	
		self.mouseCursor.move( *self.mousePosition )	

		dial = wx.MessageDialog(None, 'Czy napewno chcesz wyjść z programu?', 'Wyjście',
					wx.YES_NO | wx.NO_DEFAULT | wx.ICON_QUESTION | wx.STAY_ON_TOP)
            
		ret = dial.ShowModal()
		
		if ret == wx.ID_YES:
			if __name__ == '__main__':
				self.Destroy()
			else:
				self.parent.Destroy( )
				self.Destroy( )
		else:
			event.Veto()
			self.mousePosition = self.winWidth - 8, self.winHeight - 8
			self.mouseCursor.move( *self.mousePosition )	

	#-------------------------------------------------------------------------
	def onExit(self):

		if __name__ == '__main__':
			self.stoper.Stop ( )
			self.Destroy( )
		else:
			self.stoper.Stop( )
			self.MakeModal( False )
			self.parent.Show( True )
			self.parent.stoper.Start( self.parent.timeGap )
			self.Destroy( )
		
	#-------------------------------------------------------------------------
	def onPress(self, event):

		self.numberOfPresses += 1
		
		if self.numberOfPresses == 1:

			if self.flag == 'rest':
				self.flag = 'row'
				self.rowIteration = 0

			elif self.flag == 'row':
				
				if self.rowIteration != self.numberOfRows[ self.subSizerNumber ]:
					buttonsToHighlight = range( ( self.rowIteration - 1 ) * self.numberOfColumns[ self.subSizerNumber ], ( self.rowIteration - 1 ) * self.numberOfColumns[ self.subSizerNumber ] + self.numberOfColumns[ self.subSizerNumber ] )
				else:
					buttonsToHighlight = range( ( self.rowIteration - 1 ) * self.numberOfColumns[ self.subSizerNumber ], ( self.rowIteration - 1 ) * self.numberOfColumns[ self.subSizerNumber ] + 6 )
			
				for button in buttonsToHighlight:
					item = self.subSizers[ self.subSizerNumber ].GetItem( button )
					b = item.GetWindow( )
					b.SetBackgroundColour( self.selectionColour )
					b.SetFocus( )
					b.Update( )

				self.flag = 'columns' 
				self.rowIteration -= 1
				self.columnIteration = 0
			
			elif self.flag == 'columns' and self.rowIteration != self.numberOfRows[ self.subSizerNumber ] - 1:

				item = self.subSizers[ self.subSizerNumber ].GetItem( ( self.rowIteration ) * self.numberOfColumns[ self.subSizerNumber ] + self.columnIteration - 1 )
				b = item.GetWindow( )
				b.SetBackgroundColour( self.selectionColour )
				b.SetFocus( )
				b.Update( )

				label = self.labels[ self.subSizerNumber ][ self.rowIteration * self.numberOfColumns[ self.subSizerNumber ] + self.columnIteration - 1 ]
				
				if label == 'SPECIAL_CHARACTERS':								

					self.subSizerNumber = 1

					self.mainSizer.Show( item = self.subSizers[ 1 ], show = True, recursive = True )
					self.mainSizer.Show( item = self.subSizers[ 0 ], show = False, recursive = True )					
					self.SetSizer( self.mainSizer )
					
					self.Layout( )

				else:
					self.typewriterKeySound.play( )
					
					#self.typingSound.Play(wx.SOUND_ASYNC) doesn't work. Wonder why
					
					self.textField.AppendText( label )
				
				self.flag = 'row'
				self.rowIteration = 0
				self.columnIteration = 0
				self.countColumns = 0

			elif self.flag == 'columns' and self.rowIteration == self.numberOfRows[ self.subSizerNumber ] - 1:
			
				item = self.subSizers[ self.subSizerNumber ].GetItem( ( self.rowIteration ) * self.numberOfColumns[ self.subSizerNumber ] + self.columnIteration-1 )
				b = item.GetWindow( )
				b.SetBackgroundColour( self.selectionColour )
				b.SetFocus( )
				b.Update( )
				
				label = self.labels[ self.subSizerNumber ][ self.rowIteration * self.numberOfColumns[ self.subSizerNumber ] + self.columnIteration-1 ]
				
				if label == 'UNDO':
					self.typewriterForwardSound.play( )
					self.textField.Remove( self.textField.GetLastPosition( ) - 1, self.textField.GetLastPosition( ) )
				
				elif label == 'SPEAK':								
					text = str( self.textField.GetValue( ) )
					
					if text == '' or text.isspace( ):
						pass

					else:
						inputTable = '~!#$&( )[]{}<>;:"\|'
						outputTable = ' ' * len( inputTable )
						translateTable = maketrans( inputTable, outputTable )
						textToSpeech = text.translate( translateTable )

						replacements = { '-' : ' minus ', '+' : ' plus ', '*' : ' razy ', '/' : ' podzielić na ', '=' : ' równa się ', '%' : ' procent ' }
						textToSpeech = reduce( lambda text, replacer: text.replace( *replacer ), replacements.iteritems( ), textToSpeech )
						
						time.sleep( 1 )
						os.system( 'milena_say %s' %textToSpeech )
				
				elif label == 'SAVE':
					text = str( self.textField.GetValue( ) )
					
					if text == '':
						pass
					else:
						f = open( 'myTextFile.txt', 'w' )
						f.write( self.textField.GetValue( ) )
						f.close( )

				elif label == 'SPACJA':
					self.typewriterSpaceSound.play( )
					self.textField.AppendText( ' ' )
				
				elif label == 'OPEN':
					try:
						textToLoad = open( 'myFile.txt' ).read( )
						self.textField.Clear( )
						self.textField.AppendText( textToLoad )

					except IOError:
						pass

	 			elif label == 'EXIT':
					if self.subSizerNumber == 0:
						self.onExit( )

					else:	
                                            self.mainSizer.Show( item = self.subSizers[ self.subSizerNumber ], show = False, recursive = True )
                                            
                                            self.subSizerNumber = 0
                                            self.mainSizer.Show( item = self.subSizers[ self.subSizerNumber ], show = True, recursive = True )
                                            
                                            self.SetSizer( self.mainSizer )
                                            self.Layout( )
                                            
                                self.flag = 'row'
				self.rowIteration = 0
				self.columnIteration = 0
				self.countRows = 0
				self.countColumns = 0

		else:
			event.Skip( ) #Event skip use in else statement here!			
	
	#-------------------------------------------------------------------------
	def timerUpdate(self, event):

		self.mouseCursor.move( *self.mousePosition )
		
		self.numberOfPresses = 0		

		if self.flag == 'row':

			if self.countRows == self.maxNumberOfRows:
				self.flag = 'rest'
				self.countRows = 0
				
				items = self.subSizers[ self.subSizerNumber ].GetChildren( )
				for item in items:
					b = item.GetWindow( )
					b.SetBackgroundColour( self.backgroundColour )
					b.SetFocus( )
					b.Update( )

			else:
				self.rowIteration = self.rowIteration % self.numberOfRows[ self.subSizerNumber ]

				items = self.subSizers[ self.subSizerNumber ].GetChildren( )
				for item in items:
					b = item.GetWindow( )
					b.SetBackgroundColour( self.backgroundColour )
					b.SetFocus( )
					b.Update( )

				if self.rowIteration == self.numberOfRows[ self.subSizerNumber ] - 1:
					self.countRows += 1
					buttonsToHighlight = range( self.rowIteration * self.numberOfColumns[ self.subSizerNumber ], self.rowIteration * self.numberOfColumns[ self.subSizerNumber ] + 6 )
				
				else:
					buttonsToHighlight = range( self.rowIteration * self.numberOfColumns[ self.subSizerNumber ], self.rowIteration * self.numberOfColumns[ self.subSizerNumber ] + self.numberOfColumns[ self.subSizerNumber ] )
					
				for button in buttonsToHighlight:
					item = self.subSizers[ self.subSizerNumber ].GetItem( button )
					b = item.GetWindow( )
					b.SetBackgroundColour( self.scanningColour )
					b.SetFocus( )
					b.Update( )

				self.rowIteration += 1
				
				if self.voice == 'True':
					os.system( 'milena_say %i' % ( self.rowIteration ) )

		elif self.flag == 'columns':

				if self.countColumns == self.maxNumberOfColumns:
					self.flag = 'row'

					item = self.subSizers[ self.subSizerNumber ].GetItem( self.rowIteration * self.numberOfColumns[ self.subSizerNumber ] + self.columnIteration - 1 )
					b = item.GetWindow( )
					b.SetBackgroundColour( self.backgroundColour )

					self.rowIteration = 0
					self.columnIteration = 0
					self.countColumns = 0

				else:
					if self.columnIteration == self.numberOfColumns[ self.subSizerNumber ] - 1 or (self.subSizerNumber == 0 and self.columnIteration == self.numberOfColumns[ self.subSizerNumber ] - 3 and self.rowIteration == self.numberOfRows[ self.subSizerNumber ] - 1 ) or ( self.subSizerNumber == 1 and self.columnIteration == self.numberOfColumns[ self.subSizerNumber ] - 4 and self.rowIteration == self.numberOfRows[ self.subSizerNumber ] - 1 ):
						self.countColumns += 1

					if self.columnIteration == self.numberOfColumns[ self.subSizerNumber ] or ( self.subSizerNumber == 0 and self.columnIteration == self.numberOfColumns[ self.subSizerNumber ] - 2 and self.rowIteration == self.numberOfRows[ self.subSizerNumber ] - 1 ) or ( self.subSizerNumber == 1 and self.columnIteration == self.numberOfColumns[ self.subSizerNumber ] - 3 and self.rowIteration == self.numberOfRows[ self.subSizerNumber ] - 1 ):
						self.columnIteration = 0

					items = self.subSizers[ self.subSizerNumber ].GetChildren( )
					for item in items:
						b = item.GetWindow( )
						b.SetBackgroundColour( self.backgroundColour )
						b.SetFocus( )
						b.Update( )

					item = self.subSizers[ self.subSizerNumber ].GetItem( self.rowIteration * self.numberOfColumns[ self.subSizerNumber ] + self.columnIteration )
					b = item.GetWindow( )
					b.SetBackgroundColour( self.scanningColour )
					b.SetFocus( )
					b.Update( )

					if self.voice == 'True':
						label = self.labels[ self.subSizerNumber ][ self.rowIteration * self.numberOfColumns[ self.subSizerNumber ] + self.columnIteration ]

						try:
							soundIndex = self.phoneLabels.index( [ item for item in self.phoneLabels if item == label ][ 0 ] )
							sound = self.sounds[ soundIndex ]
							sound.play( )
							
						except IndexError:
							pass
					
					self.columnIteration += 1

		else:
			pass
Example #32
0
class music(wx.Frame):
    def __init__(self, parent, id):

        self.winWidth, self.winHeight = wx.DisplaySize()

        wx.Frame.__init__(self, parent, id, 'music')
        style = self.GetWindowStyle()
        self.SetWindowStyle(style | wx.STAY_ON_TOP)
        self.parent = parent

        self.Maximize(True)
        self.Centre(True)
        self.MakeModal(True)

        self.initializeParameters()
        self.initializeBitmaps()
        self.createGui()
        self.initializeTimer()
        self.createBindings()

    #-------------------------------------------------------------------------
    def initializeParameters(self):

        with open('./.pathToATPlatform', 'r') as textFile:
            self.pathToATPlatform = textFile.readline()

        with open(self.pathToATPlatform + 'parameters', 'r') as parametersFile:
            for line in parametersFile:

                if line[:line.find('=') - 1] == 'timeGap':
                    self.timeGap = int(line[line.rfind('=') + 2:-1])
                elif line[:line.find('=') - 1] == 'backgroundColour':
                    self.backgroundColour = line[line.rfind('=') + 2:-1]
                elif line[:line.find('=') - 1] == 'textColour':
                    self.textColour = line[line.rfind('=') + 2:-1]
                elif line[:line.find('=') - 1] == 'scanningColour':
                    self.scanningColour = line[line.rfind('=') + 2:-1]
                elif line[:line.find('=') - 1] == 'selectionColour':
                    self.selectionColour = line[line.rfind('=') + 2:-1]
                elif line[:line.find('=') - 1] == 'filmVolume':
                    self.filmVolumeLevel = int(line[line.rfind('=') + 2:-1])
                elif line[:line.find('=') - 1] == 'musicVolume':
                    self.musicVolumeLevel = int(line[line.rfind('=') + 2:-1])

                elif not line.isspace():
                    print 'Niewłaściwie opisane parametry'
                    print 'Błąd w linii', line

                    self.timeGap = 1500
                    self.backgroundColour = 'white'
                    self.textColour = 'black'
                    self.scanningColour = '#E7FAFD'
                    self.selectionColour = '#9EE4EF'
                    self.filmVolumeLevel = 100
                    self.musicVolumeLevel = 70

        alsaaudio.Mixer(control='Master').setvolume(self.musicVolumeLevel, 0)

        self.numberOfRows = 4,
        self.numberOfColumns = 6,

        self.columnIteration = 0
        self.rowIteration = 0
        self.panelIteration = 0
        self.emptyColumnIteration = 0
        self.emptyRowIteration = 0
        self.emptyPanelIteration = 0
        self.maxEmptyColumnIteration = 2
        self.maxEmptyRowIteration = 2
        self.maxEmptyPanelIteration = 2

        self.numberOfPresses = 1

        self.mouseCursor = PyMouse()
        self.mousePosition = self.winWidth - 8, self.winHeight - 8
        self.mouseCursor.move(*self.mousePosition)

        self.SetBackgroundColour('black')

    #-------------------------------------------------------------------------
    def initializeBitmaps(self):

        try:
            self.path = self.pathToATPlatform + 'multimedia/music/'
            directories = [
                directory for directory in os.listdir(self.path)
                if os.path.isdir(os.path.join(self.path, directory))
            ]
            #directories.sort( key=lambda directory: os.path.getmtime( os.path.join(self.path, directory) ) )

            directories = sorted(directories,
                                 key=lambda x: int(x.split("_")[0]))

            self.existingLogos, self.existingMedia = [], []

            for item in directories:
                if 'playlist.m3u' in os.listdir(self.path + item):

                    self.existingMedia.append(self.path + item +
                                              '/playlist.m3u')
                    self.existingLogos.append(self.path + item + '/cover.jpg')

                else:
                    ositem = item.replace(' ',
                                          '\ ').replace('(', '\(').replace(
                                              ')', '\)').replace('&', '\&')
                    os.system('ls -d -1 %s/*.mp3 > %s/playlist.m3u' %
                              (self.path.replace(' ', '\ ') + ositem,
                               self.path.replace(' ', '\ ') + ositem))

                    self.existingMedia.append(self.path + item +
                                              '/playlist.m3u')
                    self.existingLogos.append(self.path + item + '/cover.jpg')

            self.numberOfPanels = 1 + len(self.existingMedia) / (
                (self.numberOfRows[0] - 1) * self.numberOfColumns[0] + 1)

            self.newHeight = 0.9 * self.winHeight / self.numberOfRows[0]

            self.panels = {}

            for number in range(self.numberOfPanels):
                logoNames = self.existingLogos[number *
                                               (self.numberOfRows[0] - 1) *
                                               self.numberOfColumns[0]:
                                               (number + 1) *
                                               (self.numberOfRows[0] - 1) *
                                               self.numberOfColumns[0]]

                logos = [
                    wx.ImageFromStream(open(logo, "rb")) for logo in logoNames
                ]
                logos = [
                    logo.Rescale(
                        logo.GetSize()[0] *
                        (self.newHeight / float(logo.GetSize()[1])),
                        self.newHeight, wx.IMAGE_QUALITY_HIGH)
                    for logo in logos
                ]
                logoBitmaps = [wx.BitmapFromImage(logo) for logo in logos]

                self.panels[number + 1] = [logoNames, logoBitmaps]

        except OSError:
            self.panels = {1: [[], []]}
            self.numberOfPanels = 1
            print "Błąd w strukturze plików."

        self.functionButtonPath = [
            wx.BitmapFromImage(
                wx.ImageFromStream(
                    open(self.pathToATPlatform + 'icons/volume down.png',
                         'rb'))),
            wx.BitmapFromImage(
                wx.ImageFromStream(
                    open(self.pathToATPlatform + 'icons/volume up.png',
                         'rb'))),
            wx.BitmapFromImage(
                wx.ImageFromStream(
                    open(self.pathToATPlatform + 'icons/show.png', 'rb'))),
            wx.BitmapFromImage(
                wx.ImageFromStream(
                    open(self.pathToATPlatform + 'icons/delete.png', 'rb'))),
            wx.BitmapFromImage(
                wx.ImageFromStream(
                    open(self.pathToATPlatform + 'icons/back.png', 'rb')))
        ]

        if self.numberOfPanels == 1:
            self.flag = 'row'
        else:
            self.flag = 'panel'

    #-------------------------------------------------------------------------
    def createGui(self):

        self.subSizers = []
        self.mainSizer = wx.BoxSizer(wx.VERTICAL)

        self.numberOfCells = self.numberOfRows[0] * self.numberOfColumns[0]
        for panel in self.panels.keys():

            subSizer = wx.GridBagSizer(4, 4)

            self.subSizers.append(subSizer)

            if self.panels != {1: [[], []]}:

                index = 0
                for index, logo in enumerate(self.panels[panel][1]):
                    b = bt.GenBitmapButton(self,
                                           -1,
                                           name=self.panels[panel][0][index],
                                           bitmap=logo)
                    b.SetBackgroundColour(self.backgroundColour)
                    b.SetBezelWidth(3)
                    b.Bind(wx.EVT_LEFT_DOWN, self.onPress)
                    subSizer.Add(b, (index / self.numberOfColumns[0],
                                     index % self.numberOfColumns[0]),
                                 wx.DefaultSpan, wx.EXPAND)
            else:
                index = -1

            index_2 = 0
            while index + index_2 < self.numberOfCells - 7:
                index_2 += 1
                b = bt.GenButton(self, -1)
                b.Bind(wx.EVT_LEFT_DOWN, self.onPress)
                b.SetBackgroundColour(self.backgroundColour)
                subSizer.Add(b, ((index + index_2) / self.numberOfColumns[0],
                                 (index + index_2) % self.numberOfColumns[0]),
                             wx.DefaultSpan, wx.EXPAND)

            b = bt.GenBitmapButton(self, -1, bitmap=self.functionButtonPath[0])
            b.SetBackgroundColour(self.backgroundColour)
            b.SetBezelWidth(3)
            b.Bind(wx.EVT_LEFT_DOWN, self.onPress)
            subSizer.Add(b, ((index + index_2 + 1) / self.numberOfColumns[0],
                             (index + index_2 + 1) % self.numberOfColumns[0]),
                         wx.DefaultSpan, wx.EXPAND)

            b = bt.GenBitmapButton(self, -1, bitmap=self.functionButtonPath[1])
            b.SetBackgroundColour(self.backgroundColour)
            b.SetBezelWidth(3)
            b.Bind(wx.EVT_LEFT_DOWN, self.onPress)
            subSizer.Add(b, ((index + index_2 + 2) / self.numberOfColumns[0],
                             (index + index_2 + 2) % self.numberOfColumns[0]),
                         wx.DefaultSpan, wx.EXPAND)

            b = bt.GenBitmapButton(self, -1, bitmap=self.functionButtonPath[2])
            b.SetBackgroundColour(self.backgroundColour)
            b.SetBezelWidth(3)
            b.Bind(wx.EVT_LEFT_DOWN, self.onPress)
            subSizer.Add(b, ((index + index_2 + 3) / self.numberOfColumns[0],
                             (index + index_2 + 3) % self.numberOfColumns[0]),
                         (1, 2), wx.EXPAND)

            b = bt.GenBitmapButton(self, -1, bitmap=self.functionButtonPath[3])
            b.SetBackgroundColour(self.backgroundColour)
            b.SetBezelWidth(3)
            b.Bind(wx.EVT_LEFT_DOWN, self.onPress)
            subSizer.Add(b, ((index + index_2 + 5) / self.numberOfColumns[0],
                             (index + index_2 + 5) % self.numberOfColumns[0]),
                         wx.DefaultSpan, wx.EXPAND)

            b = bt.GenBitmapButton(self, -1, bitmap=self.functionButtonPath[4])
            b.SetBackgroundColour(self.backgroundColour)
            b.SetBezelWidth(3)
            b.Bind(wx.EVT_LEFT_DOWN, self.onPress)
            subSizer.Add(b, ((index + index_2 + 6) / self.numberOfColumns[0],
                             (index + index_2 + 6) % self.numberOfColumns[0]),
                         wx.DefaultSpan, wx.EXPAND)

            for number in range(self.numberOfRows[0] - 1):
                subSizer.AddGrowableRow(number)
            for number in range(self.numberOfColumns[0]):
                subSizer.AddGrowableCol(number)

            self.Layout()

            self.mainSizer.Add(subSizer, proportion=1, flag=wx.EXPAND)

            self.SetSizer(self.mainSizer)
            self.Center(True)

            if panel != 1:
                self.mainSizer.Show(item=self.subSizers[panel - 1],
                                    show=False,
                                    recursive=True)

            self.SetSizer(self.mainSizer)

    #-------------------------------------------------------------------------
    def initializeTimer(self):
        self.stoper = wx.Timer(self)
        self.Bind(wx.EVT_TIMER, self.timerUpdate, self.stoper)
        self.stoper.Start(self.timeGap)

    #-------------------------------------------------------------------------
    def createBindings(self):
        self.Bind(wx.EVT_CLOSE, self.OnCloseWindow)

    #-------------------------------------------------------------------------
    def OnCloseWindow(self, event):

        self.mousePosition = self.winWidth / 1.85, self.winHeight / 1.85
        self.mouseCursor.move(*self.mousePosition)

        dial = wx.MessageDialog(
            None, 'Czy napewno chcesz wyjść z programu?', 'Wyjście',
            wx.YES_NO | wx.NO_DEFAULT | wx.ICON_QUESTION | wx.STAY_ON_TOP)

        ret = dial.ShowModal()

        if ret == wx.ID_YES:
            os.system('smplayer -send-action quit')

            if __name__ == '__main__':
                self.Destroy()
            else:
                self.parent.Destroy()
                self.Destroy()
        else:
            event.Veto()
            self.mousePosition = self.winWidth - 8, self.winHeight - 8
            self.mouseCursor.move(*self.mousePosition)

    #-------------------------------------------------------------------------
    def onExit(self):
        if __name__ == '__main__':
            self.stoper.Stop()
            self.Destroy()
        else:
            self.stoper.Stop()
            self.MakeModal(False)
            self.parent.Show(True)
            self.parent.stoper.Start(self.parent.timeGap)
            self.Destroy()

    #-------------------------------------------------------------------------
    def onPress(self, event):

        self.numberOfPresses += 1

        if self.numberOfPresses == 1:

            if self.flag == 'rest':

                if self.numberOfPanels == 1:
                    self.flag = 'row'
                else:
                    self.flag = 'panel'

            elif self.flag == 'panel':
                items = self.subSizers[self.panelIteration].GetChildren()

                for item in items:
                    b = item.GetWindow()
                    b.SetBackgroundColour(self.scanningColour)
                    b.SetFocus()

                self.flag = 'row'

            elif self.flag == 'row':

                if self.rowIteration == self.numberOfRows[0]:
                    buttonsToHighlight = range(
                        (self.rowIteration - 1) * self.numberOfColumns[0],
                        (self.rowIteration - 1) * self.numberOfColumns[0] +
                        self.numberOfColumns[0] - 1)

                else:
                    buttonsToHighlight = range(
                        (self.rowIteration - 1) * self.numberOfColumns[0],
                        (self.rowIteration - 1) * self.numberOfColumns[0] +
                        self.numberOfColumns[0])

                for button in buttonsToHighlight:
                    item = self.subSizers[self.panelIteration].GetItem(button)
                    b = item.GetWindow()
                    b.SetBackgroundColour(self.selectionColour)
                    b.SetFocus()

                self.flag = 'columns'

            elif self.flag == 'columns':

                self.position = (
                    self.rowIteration -
                    1) * self.numberOfColumns[0] + self.columnIteration - 1

                item = self.subSizers[self.panelIteration].GetItem(
                    self.position)
                selectedButton = item.GetWindow()
                selectedButton.SetBackgroundColour(self.selectionColour)
                selectedButton.SetFocus()

                self.Update()

                if self.rowIteration == self.numberOfRows[0]:

                    if self.columnIteration == 1:
                        try:
                            recentVolume = alsaaudio.Mixer(
                                control='Master').getvolume()[0]
                            alsaaudio.Mixer(control='Master').setvolume(
                                recentVolume - 15, 0)
                            time.sleep(1.5)

                        except alsaaudio.ALSAAudioError:
                            selectedButton.SetBackgroundColour('red')
                            selectedButton.SetFocus()

                            self.Update()
                            time.sleep(1.5)

                    elif self.columnIteration == 2:
                        try:
                            recentVolume = alsaaudio.Mixer(
                                control='Master').getvolume()[0]
                            alsaaudio.Mixer(control='Master').setvolume(
                                recentVolume + 15, 0)
                            time.sleep(1.5)

                        except alsaaudio.ALSAAudioError:
                            selectedButton.SetBackgroundColour('red')
                            selectedButton.SetFocus()

                            self.Update()
                            time.sleep(1.5)

                    elif self.columnIteration == 3:
                        self.stoper.Stop()
                        musicPilot.pilot(self, id=2).Show(True)
                        self.Hide()

                    elif self.columnIteration == 4:
                        os.system('smplayer -send-action quit &')

                    elif self.columnIteration == 5:
                        self.onExit()
                else:
                    try:

                        logo = self.panels[self.panelIteration +
                                           1][0][self.position]

                        videoIndex = self.existingLogos.index(logo)
                        choice = self.existingMedia[videoIndex]
                        os.system('smplayer -pos 0 0 %s &' %
                                  choice.replace(' ', r'\ ').replace(
                                      '&', r'\&').replace('#', r'\#').replace(
                                          '(', r'\(').replace(')', r'\)'))

                    except IndexError:
                        selectedButton.SetBackgroundColour('red')
                        selectedButton.SetFocus()

                        self.Update()
                        time.sleep(1.5)

                if self.numberOfPanels == 1:
                    self.flag = 'row'
                    self.panelIteration = 0
                else:
                    self.flag = 'panel'
                    self.panelIteration = -1

                self.rowIteration = 0
                self.columnIteration = 0

                self.emptyPanelIteration = -1
                self.emptyRowIteration = 0
                self.emptyColumnIteration = 0

                selectedButton = item.GetWindow()
                selectedButton.SetBackgroundColour(self.backgroundColour)
                selectedButton.SetFocus()

        else:
            pass

        # print self.numberOfPresses

    #-------------------------------------------------------------------------
    def timerUpdate(self, event):

        self.mouseCursor.move(*self.mousePosition)

        self.numberOfPresses = 0

        if self.flag == 'panel':  ## flag == panel ie. switching between panels

            if self.emptyPanelIteration == self.maxEmptyPanelIteration:
                self.flag = 'rest'
                self.emptyPanelIteration = 0
            else:
                self.panelIteration += 1
                self.panelIteration = self.panelIteration % self.numberOfPanels

                if self.panelIteration == self.numberOfPanels - 1:
                    self.emptyPanelIteration += 1

                for item in range(self.numberOfPanels):
                    if item != self.panelIteration:
                        self.mainSizer.Show(item=self.subSizers[item],
                                            show=False,
                                            recursive=True)

                self.mainSizer.Show(item=self.subSizers[self.panelIteration],
                                    show=True,
                                    recursive=True)
                self.SetSizer(self.mainSizer)
                self.Layout()

        if self.flag == 'row':  #flag == row ie. switching between rows

            if self.emptyRowIteration == self.maxEmptyRowIteration:
                self.emptyRowIteration = 0
                self.emptyPanelIteration = 0

                if self.numberOfPanels == 1:
                    self.flag = 'rest'
                else:
                    self.flag = 'panel'

                items = self.subSizers[self.panelIteration].GetChildren()
                for item in items:
                    b = item.GetWindow()
                    b.SetBackgroundColour(self.backgroundColour)
                    b.SetFocus()
#####################################################################################################################################

                if self.numberOfPanels > 1:
                    if self.panelIteration == self.numberOfPanels:
                        self.panelIteration = self.numberOfPanels - 1
                    else:
                        self.panelIteration -= 1

######################################################################################################################################
            else:
                self.rowIteration = self.rowIteration % self.numberOfRows[0]

                items = self.subSizers[self.panelIteration].GetChildren()
                for item in items:
                    b = item.GetWindow()
                    b.SetBackgroundColour(self.backgroundColour)
                    b.SetFocus()

                if self.rowIteration == self.numberOfRows[0] - 1:
                    self.emptyRowIteration += 1

                    scope = range(
                        self.rowIteration * self.numberOfColumns[0],
                        self.rowIteration * self.numberOfColumns[0] +
                        self.numberOfColumns[0] - 1)
                else:
                    scope = range(
                        self.rowIteration * self.numberOfColumns[0],
                        self.rowIteration * self.numberOfColumns[0] +
                        self.numberOfColumns[0])

                for i in scope:
                    item = self.subSizers[self.panelIteration].GetItem(i)
                    b = item.GetWindow()
                    b.SetBackgroundColour(self.scanningColour)
                    b.SetFocus()
                self.rowIteration += 1

        elif self.flag == 'columns':  #flag = columns ie. switching between cells in the particular row

            if self.emptyColumnIteration == self.maxEmptyColumnIteration:
                self.flag = 'row'
                self.rowIteration = 0
                self.columnIteration = 0
                self.emptyColumnIteration = 0
                self.emptyRowIteration = 0

                items = self.subSizers[self.panelIteration].GetChildren()
                for item in items:
                    b = item.GetWindow()
                    b.SetBackgroundColour(self.backgroundColour)
                    b.SetFocus()

            else:
                if self.rowIteration == self.numberOfRows[0]:
                    self.columnIteration = self.columnIteration % (
                        self.numberOfColumns[0] - 1)

                    if self.columnIteration == self.numberOfColumns[0] - 2:
                        self.emptyColumnIteration += 1

                else:
                    self.columnIteration = self.columnIteration % self.numberOfColumns[
                        0]

                    if self.columnIteration == self.numberOfColumns[0] - 1:
                        self.emptyColumnIteration += 1

                items = self.subSizers[self.panelIteration].GetChildren()
                for item in items:
                    b = item.GetWindow()
                    b.SetBackgroundColour(self.backgroundColour)
                    b.SetFocus()

                item = self.subSizers[self.panelIteration].GetItem(
                    (self.rowIteration - 1) * self.numberOfColumns[0] +
                    self.columnIteration)
                b = item.GetWindow()
                b.SetBackgroundColour(self.scanningColour)
                b.SetFocus()

                self.columnIteration += 1
        else:
            pass
#Opencv and dependencies
import cv2
import numpy as np

#our libraries
import util as ut
import svm_train as st
import hand_util as hu

#other dependencies
from pymouse import PyMouse
from pykeyboard import PyKeyboard
import moosegesture as mges

#PyMouse the library to control mouse movements from python
m1 = PyMouse()
k1 = PyKeyboard()

#capturing device
cam = int(raw_input("Enter Camera Index : "))
cap = cv2.VideoCapture(cam)

#training the svm
model = st.trainSVM(3, 40, 'TrainData')

#initilizing values
thresh = 120
frame_count = 0
color = (0, 0, 255)
res = ut.get_screen_res()
w_screen = int(res['w']) + 200
Example #34
0
	def initializeParameters(self):
                
            with open( './.pathToATPlatform' ,'r' ) as textFile:
		    self.pathToATPlatform = textFile.readline( )
		    
	    with open( self.pathToATPlatform + 'parameters', 'r' ) as parametersFile:
		    for line in parametersFile:

			    if line[ :line.find('=')-1 ] == 'timeGap':
				    self.timeGap = int( line[ line.rfind('=')+2:-1 ] )
			    elif line[ :line.find('=')-1 ] == 'backgroundColour':
				    self.backgroundColour = line[ line.rfind('=')+2:-1 ]
			    elif line[ :line.find('=')-1 ] == 'textColour':
				    self.textColour = line[ line.rfind('=')+2:-1 ]
			    elif line[ :line.find('=')-1 ] == 'scanningColour':
				    self.scanningColour = line[ line.rfind('=')+2:-1 ]
			    elif line[ :line.find('=')-1 ] == 'selectionColour':
				    self.selectionColour = line[ line.rfind('=')+2:-1 ]
			    elif line[ :line.find('=')-1 ] == 'filmVolume':
				    self.filmVolumeLevel = int( line[ line.rfind('=')+2:-1 ] )
			    elif line[ :line.find('=')-1 ] == 'musicVolume':
			    	    self.musicVolumeLevel = int( line[ line.rfind('=')+2:-1 ] )
			
			    elif not line.isspace( ):
				    print 'Niewłaściwie opisane parametry'
				    print 'Błąd w pliku parameters w linii', line
				    
				    self.timeGap = 1500
				    self.backgroundColour = 'white'
				    self.textColour = 'black'
				    self.scanningColour =  '#E7FAFD'
				    self.selectionColour = '#9EE4EF'
				    self.filmVolumeLevel = 100
				    self.musicVolumeLevel = 40

	    with open( self.pathToATPlatform + 'spellerParameters', 'r' ) as parametersFile:
		    for line in parametersFile:

			    if line[ :line.find('=')-1 ] == 'voice':
				    self.voice = line[ line.rfind('=')+2:-1 ]
			    elif line[ :line.find('=')-1 ] == 'vowelColour':
				    self.vowelColour = line[ line.rfind('=')+2:-1 ]
			    elif line[ :line.find('=')-1 ] == 'polishLettersColour':
				    self.polishLettersColour = line[ line.rfind('=')+2:-1 ]
			
			    elif not line.isspace( ):
				    print 'Niewłaściwie opisane parametry'
				    print 'Błąd w pliku spellerParameters w linii', line
				    
				    self.voice = 'False'
				    self.vowelColour = 'False'
				    self.polishLettersColour = 'False'

	    self.labels = [ 'A E B C D F G H I O J K L M N P U Y R S T W Z SPECIAL_CHARACTERS UNDO SPEAK SAVE SPACJA OPEN EXIT'.split( ), '1 2 3 4 5 6 7 8 9 0 + - * / = % $ & . , ; : " ? ! @ # ( ) [ ] { } < > ~ UNDO SPEAK SAVE SPACJA OPEN EXIT'.split( ) ]
	    
	    self.colouredLabels = [ 'A', 'E', 'I', 'O', 'U', 'Y' ]

	    self.numberOfRows = [ 4, 5 ]
	    self.numberOfColumns = [ 8, 9 ]
				
	    self.flag = 'row'						
	    self.rowIteration = 0						
	    self.columnIteration = 0							
	    self.countRows = 0
	    self.countColumns = 0										

	    self.maxNumberOfRows = 2
	    self.maxNumberOfColumns = 2									
	    
	    self.numberOfPresses = 1
	    self.subSizerNumber = 0

	    self.mouseCursor = PyMouse( )
	    self.mousePosition = self.winWidth - 8, self.winHeight - 8
	    self.mouseCursor.move( *self.mousePosition )			

	    mixer.init( )
	    self.typewriterKeySound = mixer.Sound( self.pathToATPlatform + 'sounds/typewriter_key.wav' )
	    self.typewriterForwardSound = mixer.Sound( self.pathToATPlatform + 'sounds/typewriter_forward.wav' )
	    self.typewriterSpaceSound = mixer.Sound( self.pathToATPlatform + 'sounds/typewriter_space.wav' )

	    if self.voice == 'True':
		    self.phones = glob.glob( self.pathToATPlatform + 'sounds/phone/*' )
		    self.phoneLabels = [ item[ item.rfind( '/' )+1 : item.rfind( '.' ) ] for item in self.phones ]
		    self.sounds = [ mixer.Sound( self.sound ) for self.sound in self.phones ]
	    
	    self.SetBackgroundColour( 'black' )
Example #35
0
 def __init__(self):
     self.mouse = PyMouse()
     self.keyboard = PyKeyboard()
     self.dr = webdriver.Chrome()
     self.dr.maximize_window()
     self.dr.get('http://39.106.93.201/signIn')
Example #36
0
    def initializeParameters(self):

        with open('./.pathToAP', 'r') as textFile:
            self.pathToAP = textFile.readline()

        sys.path.append(self.pathToAP)
        from reader import reader

        reader = reader()
        reader.readParameters()
        parameters = reader.getParameters()

        for item in parameters:
            try:
                setattr(self, item[:item.find('=')],
                        int(item[item.find('=') + 1:]))
            except ValueError:
                setattr(self, item[:item.find('=')], item[item.find('=') + 1:])

        self.panelIteration = 0
        self.rowIteration = 0
        self.columnIteration = 0

        self.defaultNumberOfColumns = 6
        self.defaultNumberOfRows = 4

        self.countRows = 0
        self.countColumns = 0
        self.button = 1
        self.countMaxRows = 2
        self.countMaxColumns = 2
        self.numberOfPresses = 0

        self.numberOfSymbol = 0
        self.flag = 'panel'

        if self.control != 'tracker':
            self.mouseCursor = PyMouse()
            self.mousePosition = self.winWidth - 8 - self.xBorder, self.winHeight - 8 - self.yBorder
            self.mouseCursor.move(*self.mousePosition)

        if self.switchSound.lower() != 'off' or self.pressSound.lower(
        ) != 'off':
            mixer.init()
            self.switchingSound = mixer.Sound(self.pathToAP +
                                              '/sounds/switchSound.ogg')
            self.pressingSound = mixer.Sound(self.pathToAP +
                                             '/sounds/pressSound.ogg')

            self.oneSound = mixer.Sound(self.pathToAP + '/sounds/rows/1.ogg')
            self.twoSound = mixer.Sound(self.pathToAP + '/sounds/rows/2.ogg')
            self.powrotSound = mixer.Sound(self.pathToAP +
                                           '/sounds/powrot.ogg')
            self.pusteSound = mixer.Sound(self.pathToAP + '/sounds/puste.ogg')

            self.pageFlipSounds = glob.glob(self.pathToAP +
                                            'sounds/page_flip/*')

            self.pageFlipSound = mixer.Sound(self.pageFlipSounds[1])
            self.lastPageFlipSound = mixer.Sound(self.pathToAP +
                                                 'sounds/page-flip-13.ogg')
            self.pageFlipSounds = [
                mixer.Sound(self.pageFlipSound)
                for self.pageFlipSound in self.pageFlipSounds
            ]

        self.SetBackgroundColour('black')
Example #37
0
class LSLViewer():
    def __init__(self, stream, fig, axes, window, scale, dejitter=True):
        """Init"""
        self.stream = stream
        self.window = window
        self.scale = scale
        self.dejitter = dejitter
        self.inlet = StreamInlet(stream, max_chunklen=buf)
        self.filt = True
        self.k = PyKeyboard()
        self.m = PyMouse()
        self.xdim, self.ydim = self.m.screen_size()

        info = self.inlet.info()
        description = info.desc()

        self.sfreq = info.nominal_srate()
        self.n_samples = int(self.sfreq * self.window)
        self.n_chan = info.channel_count()

        ch = description.child('channels').first_child()
        ch_names = [ch.child_value('label')]

        for i in range(self.n_chan):
            ch = ch.next_sibling()
            ch_names.append(ch.child_value('label'))

        self.ch_names = ch_names

        fig.canvas.mpl_connect('key_press_event', self.OnKeypress)
        fig.canvas.mpl_connect('button_press_event', self.onclick)

        self.fig = fig
        self.axes = axes

        sns.despine(left=True)

        self.data = np.zeros((self.n_samples, self.n_chan))
        self.times = np.arange(-self.window, 0, 1. / self.sfreq)
        impedances = np.std(self.data, axis=0)
        lines = []

        for ii in range(self.n_chan):
            line, = axes.plot(self.times[::subsample],
                              self.data[::subsample, ii] - ii,
                              lw=1)
            lines.append(line)
        self.lines = lines

        axes.set_ylim(-self.n_chan + 0.5, 0.5)
        ticks = np.arange(0, -self.n_chan, -1)

        axes.set_xlabel('Time (s)')
        axes.set_ylabel('Average Voltage (uV)')
        axes.xaxis.grid(False)
        axes.set_yticks(ticks)

        ticks_labels = [
            '%s - %.1f' % (ch_names[ii], impedances[ii])
            for ii in range(self.n_chan)
        ]
        axes.set_yticklabels(ticks_labels)

        self.display_every = int(0.2 / (12 / self.sfreq))

        self.bf, self.af = butter(4,
                                  np.array([1, 40]) / (self.sfreq / 2.),
                                  'bandpass')
        zi = lfilter_zi(self.bf, self.af)
        self.filt_state = np.tile(zi, (self.n_chan, 1)).transpose()
        self.data_f = np.zeros((self.n_samples, self.n_chan))

    def update_plot(self):
        k = 0
        while self.started:
            samples, timestamps = self.inlet.pull_chunk(timeout=1.0,
                                                        max_samples=12)
            if timestamps:
                if self.dejitter:
                    timestamps = np.float64(np.arange(len(timestamps)))
                    timestamps /= self.sfreq
                    timestamps += self.times[-1] + 1. / self.sfreq
                self.times = np.concatenate([self.times, timestamps])
                self.n_samples = int(self.sfreq * self.window)
                self.times = self.times[-self.n_samples:]
                self.data = np.vstack([self.data, samples])
                self.data = self.data[-self.n_samples:]
                filt_samples, self.filt_state = lfilter(self.bf,
                                                        self.af,
                                                        samples,
                                                        axis=0,
                                                        zi=self.filt_state)
                self.data_f = np.vstack([self.data_f, filt_samples])
                self.data_f = self.data_f[-self.n_samples:]
                k += 1

                if k == self.display_every:

                    if self.filt:
                        plot_data = self.data_f
                    elif not self.filt:
                        plot_data = self.data - self.data.mean(axis=0)
                    #                    LC,RC,EY,WR
                    t_values = np.array([75, 75, 75, 1000])

                    print("Data\n")
                    last_100ms = np.absolute(plot_data[980:, :])
                    # print(last_100ms)
                    # print("Average\n")
                    # print(np.mean(last_100ms, axis = 0))
                    # print("Max\n")
                    # print(np.max(last_100ms, axis = 0))
                    # print("Count\n")
                    print("L, R, E, W")
                    # print(np.sum(last_100ms > t_values, axis = 0))
                    print("\n")
                    cmdArr = np.sum(last_100ms > t_values,
                                    axis=0) > [10, 7, 10, 10]
                    print(cmdArr)
                    print("\n")

                    self.k.release_key('c')
                    self.k.release_key('v')
                    self.k.release_key('z')
                    self.k.release_key('x')
                    ##Keyboard Input
                    if cmdArr[0]:  ##Mario Left
                        self.k.press_key('c')
                    if cmdArr[1]:  ##Mario Right
                        self.k.press_key('v')
                    if cmdArr[2]:  ## Mario Jump
                        self.k.press_key('z')
                    if cmdArr[3]:  ## Mario Special
                        self.k.press_key('x')

                    ####

                    for ii in range(self.n_chan):
                        self.lines[ii].set_xdata(self.times[::subsample] -
                                                 self.times[-1])
                        self.lines[ii].set_ydata(plot_data[::subsample, ii] /
                                                 self.scale - ii)
                        impedances = np.std(plot_data, axis=0)

                    ticks_labels = [
                        '%s - %.2f' % (self.ch_names[ii], impedances[ii])
                        for ii in range(self.n_chan)
                    ]
                    self.axes.set_yticklabels(ticks_labels)
                    self.axes.set_xlim(-self.window, 0)
                    self.fig.canvas.draw()
                    k = 0
            else:
                sleep(0.2)

    def onclick(self, event):
        print((event.button, event.x, event.y, event.xdata, event.ydata))

    def OnKeypress(self, event):
        if event.key == '/':
            self.scale *= 1.2
        elif event.key == '*':
            self.scale /= 1.2
        elif event.key == '+':
            self.window += 1
        elif event.key == '-':
            if self.window > 1:
                self.window -= 1
        elif event.key == 'd':
            self.filt = not (self.filt)

    def start(self):
        self.started = True
        self.thread = Thread(target=self.update_plot)
        self.thread.daemon = True
        self.thread.start()

    def stop(self):
        self.started = False
Example #38
0
# -*- coding: utf-8 -*-

from pymouse import PyMouse
from pykeyboard import PyKeyboard
import time
import datetime

m = PyMouse()
k = PyKeyboard()

# - - - Global Variables - - -
# 每個步驟之間,等待的秒數(也就是預期的網路延遲時間)
gl_lag = 4
# 整個 MAC 螢幕的長、寬
x_dim, y_dim = m.screen_size()
# Get focus off terminal
m.click(250, 350, 1)


# 狂點擊某個位置
def click_for_N_seconds(position, sleep_sec, n_sec):
    """
    每隔 sleep_sec 就點擊一次 position,持續 n_sec 秒
    因為是狂點擊的關係,sleep_sec 可以不用跟 gl_lag 一樣沒關係
    """
    period = n_sec // sleep_sec
    for i in range(period):
        msg = get_time_stamp() + "clickForNSeconds(): [" + str(
            position[0]) + "," + str(position[1]) + "]\n"
        fileHandler.write(msg)
        print msg
Example #39
0
class youtube1(wx.Frame):
    def __init__(self, parent, id):

        self.winWidth, self.winHeight = wx.DisplaySize()
        self.winHeight -= 20

        wx.Frame.__init__(self, parent, id, 'APYoutube1')
        style = self.GetWindowStyle()
        self.SetWindowStyle(style | wx.STAY_ON_TOP)
        self.parent = parent

        self.Maximize(True)
        self.Centre(True)
        self.MakeModal(True)

        self.initializeParameters()
        self.initializeBitmaps()
        self.createGui()
        self.initializeTimer()
        self.createBindings()

    #-------------------------------------------------------------------------
    def initializeParameters(self):

        with open('./.pathToAP', 'r') as textFile:
            self.pathToAP = textFile.readline()

        sys.path.append(self.pathToAP)
        from reader import reader

        reader = reader()
        reader.readParameters()
        parameters = reader.getParameters()

        for item in parameters:
            try:
                setattr(self, item[:item.find('=')],
                        int(item[item.find('=') + 1:]))
            except ValueError:
                setattr(self, item[:item.find('=')], item[item.find('=') + 1:])

        self.panelIteration = 0
        self.rowIteration = 0
        self.columnIteration = 0

        self.defaultNumberOfColumns = 6
        self.defaultNumberOfRows = 4

        self.countRows = 0
        self.countColumns = 0
        self.button = 1
        self.countMaxRows = 2
        self.countMaxColumns = 2
        self.numberOfPresses = 0

        self.numberOfSymbol = 0
        self.flag = 'panel'

        if self.control != 'tracker':
            self.mouseCursor = PyMouse()
            self.mousePosition = self.winWidth - 8 - self.xBorder, self.winHeight - 8 - self.yBorder
            self.mouseCursor.move(*self.mousePosition)

        if self.switchSound.lower() != 'off' or self.pressSound.lower(
        ) != 'off':
            mixer.init()
            self.switchingSound = mixer.Sound(self.pathToAP +
                                              '/sounds/switchSound.ogg')
            self.pressingSound = mixer.Sound(self.pathToAP +
                                             '/sounds/pressSound.ogg')

            self.oneSound = mixer.Sound(self.pathToAP + '/sounds/rows/1.ogg')
            self.twoSound = mixer.Sound(self.pathToAP + '/sounds/rows/2.ogg')
            self.powrotSound = mixer.Sound(self.pathToAP +
                                           '/sounds/powrot.ogg')
            self.pusteSound = mixer.Sound(self.pathToAP + '/sounds/puste.ogg')

            self.pageFlipSounds = glob.glob(self.pathToAP +
                                            'sounds/page_flip/*')

            self.pageFlipSound = mixer.Sound(self.pageFlipSounds[1])
            self.lastPageFlipSound = mixer.Sound(self.pathToAP +
                                                 'sounds/page-flip-13.ogg')
            self.pageFlipSounds = [
                mixer.Sound(self.pageFlipSound)
                for self.pageFlipSound in self.pageFlipSounds
            ]

        self.SetBackgroundColour('black')

    #-------------------------------------------------------------------------
    def initializeBitmaps(self):

        dict = self.pathToAP + 'multimedia/youtube/*'
        pages = sorted([
            item for item in glob.glob(dict)
            if item[item.rfind('/') + 1:].isdigit()
        ])
        self.numberOfpages = len(pages)

        self.blissBook = {
        }  #dictionary with keys as number of page and values as list of tuples (each tuple discribes one symbol) in form [bitmap, bitmap's position in sizer, bitmap's label]
        self.numberOfRows, self.numberOfColumns, self.numberOfCells = [], [], []

        for page in pages:
            try:
                pageNumber = int(page[page.rfind('/') + 1:])
            except ValueError:
                print 'Folderowi %s nadano nieprawidłową nazwę. Dopuszczalna jest tylko nazwa numeryczna.' % page[
                    page.rfind('/') + 1:]
                pass

            sizerTopology = open(page + '/sizer')

            for line in sizerTopology:

                if line[:12] == 'numberOfRows':
                    self.numberOfRows.append(int(line[-2]))
                elif line[:15] == 'numberOfColumns':
                    self.numberOfColumns.append(int(line[-2]))
                else:
                    print 'Niewłaściwie opisana tablica na stronie %' % page
                    self.numberOfColumns.append(self.defaultNumberOfColumns)
                    self.numberOfRows.append(self.defaultNumberOfRows)

            symbols = glob.glob(page + '/*.jpg') + glob.glob(
                page + '/*.png') + glob.glob(page +
                                             '/*.JPG') + glob.glob(page +
                                                                   '/*jpeg')
            symbols = [item.decode('utf-8') for item in symbols]

            symbolInfo = []

            self.newHeight = 0.6 * self.winHeight / self.numberOfRows[-1]

            for symbol in symbols:

                image = wx.ImageFromStream(open(symbol, "rb"))

                self.newWidth = image.GetSize()[0] * (
                    self.newHeight / float(image.GetSize()[1]))

                image.Rescale(self.newWidth, self.newHeight,
                              wx.IMAGE_QUALITY_HIGH)
                bitmapSymbol = wx.BitmapFromImage(image)

                symbolName = symbol[symbol.rfind('/') + 1:symbol.rfind('.')]

                try:
                    symbolPosition = int(symbolName.split('_')[0])
                    symbolTranslate = symbolName[symbolName.find('_') +
                                                 1:].replace('_', ' ')
                    symbolInfo.append(
                        [bitmapSymbol, symbolPosition, symbolTranslate])
                except ValueError:
                    print 'Symbol %s w folderze %s ma nieprawidłową nazwę.' % (
                        symbolName.split('_')[0], page[page.rfind('/') + 1:])
                    pass

            symbolInfo.sort(key=lambda symbolInfo: symbolInfo[1])
            self.blissBook[pageNumber] = symbolInfo

    #-------------------------------------------------------------------------
    def createGui(self):

        self.mainSizer = wx.BoxSizer(wx.VERTICAL)

        self.panel = wx.Panel(self, 1, style=wx.SUNKEN_BORDER)
        self.panel.SetSizeWH(self.winWidth, 0.22 * self.winHeight)
        self.panelSize = self.panel.GetSize()

        self.displaySizer = wx.BoxSizer(wx.HORIZONTAL)
        self.displaySizer.SetMinSize(self.panelSize)
        self.displaySizer.Fit(self.panel)
        self.displaySizer.Add(self.panel, 1, wx.EXPAND)
        self.mainSizer.Add(self.displaySizer,
                           1,
                           wx.EXPAND | wx.BOTTOM | wx.TOP,
                           border=1)

        self.subSizers = []

        for item in range(len(self.numberOfRows)):

            subSizer = wx.GridSizer(self.numberOfRows[item],
                                    self.numberOfColumns[item], 1, 1)
            subSizer.SetMinSize(
                (self.winWidth, 0.768 * self.winHeight)
            )  #this should not be done like this. Sizer should fit automatically.

            self.subSizers.append(subSizer)

            i, j = 0, 1

            self.numberOfCells = self.numberOfRows[
                item] * self.numberOfColumns[item]

            while j <= self.numberOfCells:
                try:
                    if i < len(self.blissBook[item]):
                        while j != self.blissBook[item][i][1]:
                            b = bt.GenButton(self, -1, name='puste')
                            b.Bind(wx.EVT_LEFT_DOWN, self.onPress)
                            b.SetBackgroundColour(self.backgroundColour)
                            self.subSizers[item].Add(
                                b, 0, wx.EXPAND | wx.ALIGN_CENTER)
                            j += 1

                        b = bt.GenBitmapButton(
                            self,
                            -1,
                            bitmap=self.blissBook[item][i][0],
                            name=self.blissBook[item][i][2])
                        b.Bind(wx.EVT_LEFT_DOWN, self.onPress)
                        b.SetBackgroundColour(self.backgroundColour)
                        self.subSizers[item].Add(b, 0,
                                                 wx.EXPAND | wx.ALIGN_CENTER)
                        i += 1
                        j += 1

                    else:
                        b = bt.GenButton(self, -1, name='puste')
                        b.Bind(wx.EVT_LEFT_DOWN, self.onPress)
                        b.SetBackgroundColour(self.backgroundColour)
                        self.subSizers[item].Add(b, 0,
                                                 wx.EXPAND | wx.ALIGN_CENTER)
                        j += 1

                except IndexError:
                    print 'IndexError'
                    print i, j

            self.Layout()

            self.mainSizer.Add(self.subSizers[item],
                               proportion=0,
                               flag=wx.EXPAND | wx.LEFT,
                               border=3)

            if item != 0:
                self.mainSizer.Show(item=self.subSizers[item],
                                    show=False,
                                    recursive=True)

        self.SetSizer(self.mainSizer)

    #-------------------------------------------------------------------------
    def initializeTimer(self):
        self.stoper = wx.Timer(self)
        self.Bind(wx.EVT_TIMER, self.timerUpdate, self.stoper)
        self.stoper.Start(self.timeGap)

    #-------------------------------------------------------------------------
    def createBindings(self):
        self.Bind(wx.EVT_CLOSE, self.OnCloseWindow)

    #-------------------------------------------------------------------------
    def OnCloseWindow(self, event):

        self.mousePosition = self.winWidth / 1.85, (
            self.winHeight +
            20) / 1.85  #+20 becouse of self.winHeight -= 20 in inicializator
        self.mouseCursor.move(*self.mousePosition)

        dial = wx.MessageDialog(
            None, 'Czy napewno chcesz wyjść z programu?', 'Wyjście',
            wx.YES_NO | wx.NO_DEFAULT | wx.ICON_QUESTION | wx.STAY_ON_TOP)

        ret = dial.ShowModal()

        if ret == wx.ID_YES:
            if __name__ == '__main__':
                self.Destroy()
            else:
                self.parent.Destroy()
                self.Destroy()
        else:
            event.Veto()
            self.mousePosition = self.winWidth - 8, self.winHeight + 20 - 8  #+20 becouse of self.winHeight -= 20 in inicializator
            self.mouseCursor.move(*self.mousePosition)

    #-------------------------------------------------------------------------
    def onExit(self):

        if __name__ == '__main__':
            self.stoper.Stop()
            self.Destroy()
        else:
            self.stoper.Stop()
            self.MakeModal(False)
            self.parent.Show(True)
            self.parent.stoper.Start(self.parent.timeGap)
            self.Destroy()

    #-------------------------------------------------------------------------
    def onPress(self, event):

        if self.pressSound.lower() != 'off':
            self.pressingSound.play()

        if self.numberOfPresses == 0:

            if self.flag == 'panel':
                items = self.subSizers[self.panelIteration].GetChildren()

                for item in items:
                    b = item.GetWindow()
                    b.SetBackgroundColour(self.scanningColour)
                    b.SetFocus()
                if self.blissBook[self.panelIteration][0][
                        2] == 'EXIT' and self.panelIteration == len(
                            self.subSizers) - 1:
                    if self.pressSound.lower() == "voice":
                        self.stoper.Stop()
                        time.sleep(
                            (self.selectionTime + self.timeGap) / (1000. * 2))
                        self.powrotSound.play()
                        time.sleep(
                            (self.selectionTime + self.timeGap) / (1000. * 2))
                        self.stoper.Start(self.timeGap)
                    self.onExit()

                else:

                    self.flag = 'row'
                    self.rowIteration = 0

            elif self.flag == 'row':

                self.rowIteration -= 1

                if self.pressSound == "voice":
                    if (self.rowIteration == 0):
                        self.oneSound.play()
                    if (self.rowIteration == 1):
                        self.twoSound.play()

                buttonsToHighlight = range(
                    (self.rowIteration) *
                    self.numberOfColumns[self.panelIteration],
                    (self.rowIteration) *
                    self.numberOfColumns[self.panelIteration] +
                    self.numberOfColumns[self.panelIteration])

                for button in buttonsToHighlight:
                    item = self.subSizers[self.panelIteration].GetItem(button)
                    b = item.GetWindow()
                    b.SetBackgroundColour(self.selectionColour)
                    b.SetFocus()

                self.flag = 'columns'
                self.columnIteration = 0

            elif self.flag == 'columns':

                self.columnIteration -= 1

                item = self.subSizers[self.panelIteration].GetItem(
                    (self.rowIteration) *
                    self.numberOfColumns[self.panelIteration] +
                    self.columnIteration)
                selectedButton = item.GetWindow()

                self.Update()

                if self.pressSound == 'voice':
                    if selectedButton.GetName() == 'puste':
                        selectedButton.SetBackgroundColour("red")
                        selectedButton.SetFocus()
                        self.Update()
                        self.pusteSound.play()
                    else:
                        selectedButton.SetBackgroundColour(
                            self.selectionColour)
                        selectedButton.SetFocus()
                        cmd = "milena_say %s" % selectedButton.GetName()
                        subprocess.Popen(cmd,
                                         shell=True,
                                         stdin=subprocess.PIPE)

                        for item in self.blissBook[self.panelIteration]:

                            if item[1] == self.rowIteration * self.numberOfColumns[
                                    self.
                                    panelIteration] + self.columnIteration + 1:

                                self.bitmapSize = item[0].GetSize()

                                if self.bitmapSize[1] > 0.7 * self.panelSize[1]:
                                    image = wx.ImageFromBitmap(item[0])
                                    rescaleImage = image.Rescale(
                                        (0.7 * self.panelSize[1] /
                                         self.bitmapSize[1]) *
                                        self.bitmapSize[0],
                                        0.7 * self.panelSize[1],
                                        wx.IMAGE_QUALITY_HIGH)
                                    rescaleItem = wx.BitmapFromImage(image)

                                    b = GenSymbolTextButton(self,
                                                            -1,
                                                            bitmap=rescaleItem,
                                                            label=item[2])

                                else:
                                    b = GenSymbolTextButton(self,
                                                            -1,
                                                            bitmap=item[0],
                                                            label=item[2])

                                b.SetFont(
                                    wx.Font(21, wx.FONTFAMILY_ROMAN,
                                            wx.FONTSTYLE_NORMAL,
                                            wx.FONTWEIGHT_NORMAL, False))
                                b.SetBackgroundColour(self.backgroundColour)

                                self.displaySizer.Add(b,
                                                      0,
                                                      flag=wx.EXPAND
                                                      | wx.BOTTOM | wx.TOP
                                                      | wx.ALIGN_LEFT,
                                                      border=2)
                                self.displaySizer.Layout()

                                unicodeLabel = item[2].encode('utf-8')
                                self.lastTextLenght = len(unicodeLabel) + 1
                                os.system('minitube "%s" &' % unicodeLabel)

                                time.sleep(0.5)

                                self.numberOfSymbol += 1
                                os.system("sleep 1")

                                self.stoper.Stop()
                                self.Hide()
                                self.menu = minitubePilot.pilot(self, id=1)

                                self.menu.Show()

                                selectedButton.SetBackgroundColour(
                                    self.backgroundColour)
                                # selectedButton.SetFocus( )
                                # self.Update( )
                                # selectedButto.nSetBackgroundColour( self.backgroundColour )

                self.flag = 'panel'
                self.panelIteration = 0
                self.rowIteration = 0
                self.columnIteration = 0
                self.count = 0
                self.countRows = 0

            self.numberOfPresses += 1

    #-------------------------------------------------------------------------
    def timerUpdate(self, event):

        self.mouseCursor.move(*self.mousePosition)

        self.numberOfPresses = 0

        if self.flag == 'panel':  ## flag == panel ie. switching between panels
            self.panelIteration += 1

            if self.panelIteration == len(self.blissBook):
                self.panelIteration = 0

            if self.switchSound == "voice":
                if self.panelIteration == len(self.blissBook) - 1:
                    self.powrotSound.play()

                elif self.panelIteration == len(self.blissBook) - 2:
                    self.lastPageFlipSound.play()

                else:
                    self.pageFlipSounds[self.panelIteration %
                                        len(self.pageFlipSounds)].play()

            for item in range(len(self.blissBook)):
                if item != self.panelIteration:
                    self.mainSizer.Show(item=self.subSizers[item],
                                        show=False,
                                        recursive=True)

            self.mainSizer.Show(item=self.subSizers[self.panelIteration],
                                show=True,
                                recursive=True)

            self.SetSizer(self.mainSizer)

            self.Layout()

        if self.flag == 'row':  #flag == row ie. switching between rows

            if self.countRows == self.countMaxRows:
                self.flag = 'panel'
                self.countRows = 0

                items = self.subSizers[self.panelIteration].GetChildren()
                for item in items:
                    b = item.GetWindow()
                    b.SetBackgroundColour(self.backgroundColour)
                    b.SetFocus()

            else:
                if self.rowIteration == self.numberOfRows[self.panelIteration]:
                    self.rowIteration = 0

                if self.rowIteration == self.numberOfRows[
                        self.panelIteration] - 1:
                    self.countRows += 1

                items = self.subSizers[self.panelIteration].GetChildren()
                for item in items:
                    b = item.GetWindow()
                    b.SetBackgroundColour(self.backgroundColour)
                    b.SetFocus()

                zakres = range(
                    self.rowIteration *
                    self.numberOfColumns[self.panelIteration],
                    self.rowIteration *
                    self.numberOfColumns[self.panelIteration] +
                    self.numberOfColumns[self.panelIteration])

                for i in zakres:
                    item = self.subSizers[self.panelIteration].GetItem(i)
                    b = item.GetWindow()
                    b.SetBackgroundColour(self.scanningColour)
                    b.SetFocus()
                self.rowIteration += 1

                if self.switchSound == "voice":
                    if (self.rowIteration == 1):
                        self.oneSound.play()
                    if (self.rowIteration == 2):
                        self.twoSound.play()
                    # if (self.rowIteration == 2):
                    #     self.threeSound.play()
# os.system( 'milena_say %i' % ( self.rowIteration ) )

        elif self.flag == 'columns':  #flag = columns ie. switching between cells in the particular row

            if self.countColumns == self.countMaxColumns:
                self.flag = 'row'
                self.rowIteration = 0
                self.columnIteration = 0
                self.countColumns = 0
                self.countRows = 0

                items = self.subSizers[self.panelIteration].GetChildren()
                for item in items:
                    b = item.GetWindow()
                    b.SetBackgroundColour(self.backgroundColour)
                    b.SetFocus()

            else:
                if self.columnIteration == self.numberOfColumns[
                        self.panelIteration]:
                    self.columnIteration = 0

                if self.columnIteration == self.numberOfColumns[
                        self.panelIteration] - 1:
                    self.countColumns += 1

                items = self.subSizers[self.panelIteration].GetChildren()
                for item in items:
                    b = item.GetWindow()
                    b.SetBackgroundColour(self.backgroundColour)
                    b.SetFocus()

                item = self.subSizers[self.panelIteration].GetItem(
                    self.rowIteration *
                    self.numberOfColumns[self.panelIteration] +
                    self.columnIteration)
                b = item.GetWindow()
                b.SetBackgroundColour(self.scanningColour)
                b.SetFocus()

                self.columnIteration += 1

                if self.switchSound.lower() == 'voice':
                    if b.Name == 'puste':
                        self.pusteSound.play()
                    else:
                        cmd = "milena_say %s" % b.Name
                        subprocess.Popen(cmd,
                                         shell=True,
                                         stdin=subprocess.PIPE)

                elif self.switchSound.lower() != 'off':
                    self.switchingSound.play()
Example #40
0
import time
from collections import Counter, deque
from subprocess import Popen, PIPE

import numpy as np

try:
    from sklearn import neighbors, svm
    HAVE_SK = True
except ImportError:
    print('sklearn error: classifier support')
    HAVE_SK = False

try:
    from pymouse import PyMouse
    pmouse = PyMouse()
except:
    print('PyMouse error: No mouse support')
    pmouse = None

try:
    from pykeyboard import PyKeyboard
    pkeyboard = PyKeyboard()
except:
    print('PyKeyboard error: No keyboard support')
    pkeyboard = None

from myoraw.common import *
from myoraw.myo_raw import MyoRaw, Pose, Arm, XDirection

SUBSAMPLE = 3
Example #41
0
def autoGetList():
    m = PyMouse()
    a = m.position()    #获取当前坐标的位置(这个东西到时候可以新建个py 获取坐标)
    print(a)

    time.sleep(3)
    m.move(1080, 540)   #下拉列表位
    x = 1080
    y = 540
    try:
        for i in range(25):
            m.click(x, 540, button=1, n=1)   #点下拉列表位置
            
            time.sleep(1)
            m.click(1080, y,1,1)     #移动并且点下拉列表下一个位置 
            y = y + 10
            
            time.sleep(1) 
            m.click(1030, 875,1,2)  #移动并且左击【获取别表】
            
            time.sleep(1)
    except KeyboardInterrupt:
        print('Interrupted!')
        return
Example #42
0
    if width is None:
        r = height / float(h)
        dim = (int(w * r), height)

    else:
        r = width / float(w)
        dim = (width, int(h * r))

    resized = cv2.resize(image, dim, interpolation = inter)

    return resized

cap = cv2.VideoCapture(0)

m = PyMouse()

last_click = datetime.datetime.now()

while True:
	_, frame = cap.read()
	frame = cv2.flip(frame, 1)

	hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)

	lower_orange = np.array([0, 109, 195])
	upper_orange = np.array([17, 255, 255])
	mask_orange = cv2.inRange(hsv, lower_orange, upper_orange)

	lower_green = np.array([37, 130, 95])
	upper_green = np.array([48, 190, 173])
Example #43
0
class Image_Frame1():

    def __init__(self):
        self.mouse = PyMouse()
        self.keyboard = PyKeyboard()
        self.opencv = ImageMathOpenCV(0.8)


    #随机坐标
    def get_position(self):

        #找浏览器的窗口
        cal_window = uiautomation.WindowControl(searchDepth=1,ClassName = "MozillaWindowClass")
        if cal_window.Exists():
            result = cal_window.BoundingRectangle
            x = random.randint(100,999)
            y = random.randint(100,999)
            return x,y


    def sele(self):


        x,y = self.zb("5.png")
        # print(1)
        self.mouse.click(x,y)
        self.keyboard.type_string("java")



    def open(self):
        x,y = self.zb("6.png")

        self.mouse.click(x,y)
        time.sleep(2)

        x1,y1 = self.zb("7.png")
        print(x1,y1)
        if x1 !=- 1 and y1 !=- 1:
            print("测试成功")








    #模拟鼠标左键单击
    def left_click(self):
        x,y = self.get_position()
        self.mouse.click(x,y,button=1,n=1)
        print("在位置%d,%d左键点击"%(x,y))
        return x,y



    #鼠标左键双击
    #模拟鼠标左键双击
    def left_double_click(self):
        x,y = self.get_position()
        self.mouse.click(x,y,button=1,n=2)
        print("在位置%d,%d左键双击"%(x,y))
        return x,y




    #滚动
    def top(self,num):
        self.mouse.scroll(vertical=num)




    #输入随机字符串

     #模拟使用键盘产生随机输入
    def input_string(self):
        result = []
        x,y = self.get_position()
        self.mouse.move(x,y)
        string = ["123","456","789"]
        index = random.randint(0,len(string)-1)
        key = string[index]
        self.keyboard.type_string(key)
        print("模拟使用键盘产生随机输入%s"%(key))
        result.append(x)
        result.append(y)
        return result,key



    #键盘按键(单键和组合键)
     #模拟使用键盘随机按键
    def enter_key(self):
        result = []
        x,y = self.get_position()
        self.mouse.move(x,y)
        keys = ["a","b","c","d","r",self.keyboard.numpad_keys[2]]
        index = random.randint(0,len(keys)-1)
        key = keys[index]
        self.keyboard.press_key(key)
        self.keyboard.release_key(key)
        print("模拟使用键盘按%s键"%(key))
        result.append(x)
        result.append(y)
        return result,key





    #获取坐标  图像识别的方式
    def zb(self,img):
     x,y = self.opencv.match_opencv(img)
     return x,y
Example #44
0
            with open('../../imageUtil/opencv/move.txt',
                      'w',
                      encoding='utf-8',
                      errors="ignore") as fo:
                for i in self.mouse_list:
                    fo.write(str(i) + '\n')
                fo.flush()
            return False

    def start(self):
        with mouse.Listener(on_move=self.on_move,
                            on_click=self.on_click) as listener:
            listener.join()
            # 需要监听的鼠标事件。
            listener = mouse.Listener(on_move=self.on_move,
                                      on_click=self.on_click,
                                      suppress=False)
            # 开始监听
            listener.start()


if __name__ == '__main__':
    # move_track = Orbit(min_x=1920, max_x=1920, min_y=1080, max_y=1080)
    # move_track.start()
    m = PyMouse()
    with open('../../imageUtil/opencv/move.txt', 'r') as fo:
        for i in fo:
            m.move(eval(i)[0], eval(i)[1])
            time.sleep(0.01)
    # m.position()  # 获取当前坐标的位置
    # 鼠标移动到xy位置
Example #45
0
def sqImport(tId):
    '''if tId == 0:
            while 1:
                rc = 0
                while rc == 0:
                    rc = mqttc.loop()
                print("rc: " + str(rc))'''

    if tId == 1:
        while 1:
            global app
            global MainWindow
            app = QtWidgets.QApplication(sys.argv)
            MainWindow = QtWidgets.QMainWindow()
            ui = Ui_MainWindow()
            ui.setupUi(MainWindow)
            MainWindow.show()
            sys.exit(app.exec_())
    if tId == 2:
        #import pyautogui
        from serial import Serial
        port = 'COM53'
        baudrate = 115200
        ser = Serial(port, baudrate)
        from pymouse import PyMouse
        #pyautogui.PAUSE = 2.5
        push = 1
        counter = 0
        m = PyMouse()
        max_v = 13
        centre = max_v / 2
        threshold = max_v / 4
        j = m.position()[0]
        k = m.position()[1]
        mainv = [0, 0, 0]

        def C_value(this_value, centre):
            reading = this_value * max_v / 1024
            center = centre
            distance = reading - center
            if abs(distance) < threshold:
                distance = 0
            return distance

        while 1:
            try:
                while True:
                    value = ser.readline().decode()
                    #chop(value)
                    #value2=int(value[4:7])
                    #button=int(value[8:9])
                    '''print(mainv[0])
                  print(mainv[1])
                  print(mainv[2])'''
                    x = int(value.split('-')[1])
                    y = int(value.split('-')[0])
                    push = int(value.split('-')[2])
                    #x_max = m.screen_size()[0]
                    #y_max = m.screen_size()[1]
                    x_new = int(C_value(x, centre))
                    y_new = int(C_value(y, centre))
                    #print(x_new,y_new,push)
                    m.move(j + x_new, k + y_new)
                    j = m.position()[0]
                    k = m.position()[1]
                    if push == 0:
                        counter = 1
                    if counter - push == 0:
                        m.click(j + x_new, k + y_new)
                        counter = 0
            except:
                print('Error')
Example #46
0
	def initializeParameters(self):

            with open( './.pathToAP' ,'r' ) as textFile:
                self.pathToAP = textFile.readline( )

	    sys.path.append( self.pathToAP )
	    from reader import reader
	    
            self.reader = reader()
            self.reader.readParameters()
            parameters = self.reader.getParameters()
            self.unpackParameters(parameters)
            
            self.flag = 'row'
	    self.pressFlag = False
            self.pressedStopFlag = False
	    
            self.rowIteration = 0						
            self.colIteration = 0

            self.numberOfColumns = 2,
            self.numberOfRows = 7,

	    self.numberOfEmptyIteration = 0
            self.countRows = 0
            self.countColumns = 0
            self.countMaxRows = 2									
            self.countMaxColumns = 2									
	    self.countMaxEmptyIteration = 3
            self.numberOfPresses = 1

            self.volumeLevels = [0, 20, 40, 60, 80, 100, 120, 140, 160]
            if self.volumeLevel not in self.volumeLevels:
                raise("Wrong value of volumeLevel. Accepted values: 0, 20, 40, 60, 80, 100, 120, 140, 160")

	    if self.control != 'tracker':	    
		    self.mouseCursor = PyMouse( )
		    self.mousePosition = self.winWidth - 8 - self.xBorder, self.winHeight - 16 - self.yBorder
		    self.mouseCursor.move( *self.mousePosition )	

	    if self.switchSound.lower( ) != 'off' or self.pressSound.lower( ) != 'off':
		    mixer.init( )
                    self.switchingSound = mixer.Sound( self.pathToAP + '/sounds/switchSound.ogg' )
                    self.pressingSound = mixer.Sound( self.pathToAP + '/sounds/pressSound.ogg' )
            	    
                    self.ciszejSound = mixer.Sound( self.pathToAP + '/sounds/ciszej.ogg' )
                    self.glosniejSound = mixer.Sound( self.pathToAP + '/sounds/glosniej.ogg' )
                    self.zatrzymajGrajSound = mixer.Sound( self.pathToAP + '/sounds/zatrzymaj_graj.ogg' )
                    self.stopSound = mixer.Sound( self.pathToAP + '/sounds/stop.ogg' )
                    self.playlistSound = mixer.Sound( self.pathToAP + '/sounds/playlist.ogg' )

                    self.przewinDoPrzoduSzybkoSound = mixer.Sound( self.pathToAP + '/sounds/przewiń_do_przodu_szybko.ogg' )
                    self.przewinDoTyluSzybkoSound = mixer.Sound( self.pathToAP + '/sounds/przewiń_do_tyłu_szybko.ogg' )
                    self.przewinDoPrzoduSound = mixer.Sound( self.pathToAP + '/sounds/przewiń_do_przodu.ogg' )
                    self.przewinDoTyluSound = mixer.Sound( self.pathToAP + '/sounds/przewiń_do_tyłu.ogg' )

                    self.powtarzajUtworSound = mixer.Sound( self.pathToAP + '/sounds/powtarzaj_ten_utwór.ogg' )
                    self.powtarzajListeSound = mixer.Sound( self.pathToAP + '/sounds/powtarzaj_ten_album.ogg' )

                    self.oneSound = mixer.Sound( self.pathToAP + '/sounds/rows/1.ogg' )
                    self.twoSound = mixer.Sound( self.pathToAP + '/sounds/rows/2.ogg' )
                    self.threeSound = mixer.Sound( self.pathToAP + '/sounds/rows/3.ogg' )
                    self.fourSound = mixer.Sound( self.pathToAP + '/sounds/rows/4.ogg' )
                    self.fiveSound = mixer.Sound( self.pathToAP + '/sounds/rows/5.ogg' )
                    self.sixSound = mixer.Sound( self.pathToAP + '/sounds/rows/6.ogg' )
                    self.sevenSound = mixer.Sound( self.pathToAP + '/sounds/rows/7.ogg' )

                    self.wyjscieSound = mixer.Sound( self.pathToAP + '/sounds/wyjście.ogg' )
                    self.powrotSound = mixer.Sound( self.pathToAP + '/sounds/powrot.ogg' )
                    self.usypiamSound = mixer.Sound( self.pathToAP + '/sounds/usypiam.ogg' )

	    self.width = self.numberOfColumns[0] * 120
	    self.height = self.numberOfRows[0] * 100
Example #47
0
 def __init__(self):
     self.mouse = PyMouse()
     self.keyboard = PyKeyboard()
     self.opencv = ImageMathOpenCV(0.8)
Example #48
0
class pilot(wx.Frame):
	def __init__(self, parent, id):

	    self.winWidth, self.winHeight = wx.DisplaySize( )
	    
            self.initializeParameters( )				
            wx.Frame.__init__( self , parent , id, 'musicPilot', size = ( self.width, self.height ), pos = ( self.winWidth - self.width - self.xBorder*(self.numberOfColumns[0]-2), self.winHeight - self.height - self.xBorder*(self.numberOfRows[0]-6) ) )
            self.SetBackgroundColour( 'black' )
	    
            style = self.GetWindowStyle( )
            self.SetWindowStyle( style | wx.STAY_ON_TOP )
	    self.parent = parent
            
	    self.MakeModal( True )		
	    
            self.initializeBitmaps( )
            self.createGui( )								
            self.createBindings( )						

            self.initializeTimer( )					

	#-------------------------------------------------------------------------
	def initializeParameters(self):

            with open( './.pathToAP' ,'r' ) as textFile:
                self.pathToAP = textFile.readline( )

	    sys.path.append( self.pathToAP )
	    from reader import reader
	    
            self.reader = reader()
            self.reader.readParameters()
            parameters = self.reader.getParameters()
            self.unpackParameters(parameters)
            
            self.flag = 'row'
	    self.pressFlag = False
            self.pressedStopFlag = False
	    
            self.rowIteration = 0						
            self.colIteration = 0

            self.numberOfColumns = 2,
            self.numberOfRows = 7,

	    self.numberOfEmptyIteration = 0
            self.countRows = 0
            self.countColumns = 0
            self.countMaxRows = 2									
            self.countMaxColumns = 2									
	    self.countMaxEmptyIteration = 3
            self.numberOfPresses = 1

            self.volumeLevels = [0, 20, 40, 60, 80, 100, 120, 140, 160]
            if self.volumeLevel not in self.volumeLevels:
                raise("Wrong value of volumeLevel. Accepted values: 0, 20, 40, 60, 80, 100, 120, 140, 160")

	    if self.control != 'tracker':	    
		    self.mouseCursor = PyMouse( )
		    self.mousePosition = self.winWidth - 8 - self.xBorder, self.winHeight - 16 - self.yBorder
		    self.mouseCursor.move( *self.mousePosition )	

	    if self.switchSound.lower( ) != 'off' or self.pressSound.lower( ) != 'off':
		    mixer.init( )
                    self.switchingSound = mixer.Sound( self.pathToAP + '/sounds/switchSound.ogg' )
                    self.pressingSound = mixer.Sound( self.pathToAP + '/sounds/pressSound.ogg' )
            	    
                    self.ciszejSound = mixer.Sound( self.pathToAP + '/sounds/ciszej.ogg' )
                    self.glosniejSound = mixer.Sound( self.pathToAP + '/sounds/glosniej.ogg' )
                    self.zatrzymajGrajSound = mixer.Sound( self.pathToAP + '/sounds/zatrzymaj_graj.ogg' )
                    self.stopSound = mixer.Sound( self.pathToAP + '/sounds/stop.ogg' )
                    self.playlistSound = mixer.Sound( self.pathToAP + '/sounds/playlist.ogg' )

                    self.przewinDoPrzoduSzybkoSound = mixer.Sound( self.pathToAP + '/sounds/przewiń_do_przodu_szybko.ogg' )
                    self.przewinDoTyluSzybkoSound = mixer.Sound( self.pathToAP + '/sounds/przewiń_do_tyłu_szybko.ogg' )
                    self.przewinDoPrzoduSound = mixer.Sound( self.pathToAP + '/sounds/przewiń_do_przodu.ogg' )
                    self.przewinDoTyluSound = mixer.Sound( self.pathToAP + '/sounds/przewiń_do_tyłu.ogg' )

                    self.powtarzajUtworSound = mixer.Sound( self.pathToAP + '/sounds/powtarzaj_ten_utwór.ogg' )
                    self.powtarzajListeSound = mixer.Sound( self.pathToAP + '/sounds/powtarzaj_ten_album.ogg' )

                    self.oneSound = mixer.Sound( self.pathToAP + '/sounds/rows/1.ogg' )
                    self.twoSound = mixer.Sound( self.pathToAP + '/sounds/rows/2.ogg' )
                    self.threeSound = mixer.Sound( self.pathToAP + '/sounds/rows/3.ogg' )
                    self.fourSound = mixer.Sound( self.pathToAP + '/sounds/rows/4.ogg' )
                    self.fiveSound = mixer.Sound( self.pathToAP + '/sounds/rows/5.ogg' )
                    self.sixSound = mixer.Sound( self.pathToAP + '/sounds/rows/6.ogg' )
                    self.sevenSound = mixer.Sound( self.pathToAP + '/sounds/rows/7.ogg' )

                    self.wyjscieSound = mixer.Sound( self.pathToAP + '/sounds/wyjście.ogg' )
                    self.powrotSound = mixer.Sound( self.pathToAP + '/sounds/powrot.ogg' )
                    self.usypiamSound = mixer.Sound( self.pathToAP + '/sounds/usypiam.ogg' )

	    self.width = self.numberOfColumns[0] * 120
	    self.height = self.numberOfRows[0] * 100

	#-------------------------------------------------------------------------	
        def unpackParameters(self, parameters):
		for item in parameters:
			try:
				setattr(self, item[:item.find('=')], int(item[item.find('=')+1:]))
			except ValueError:
				setattr(self, item[:item.find('=')], item[item.find('=')+1:])			

        #-------------------------------------------------------------------------	
        def initializeBitmaps(self):

            buttonPaths = glob.glob( self.pathToAP + 'icons/pilots/musicPilot/*' ) #labelFiles
            
            self.buttons = { }

            for buttonPath in buttonPaths:

                buttonBitmap = wx.BitmapFromImage( wx.ImageFromStream( open(buttonPath, "rb") ) )

                buttonLabel = buttonPath[ buttonPath.rfind( '/' )+1 : buttonPath.rfind('.') ]
                try:
                    buttonPosition = int( buttonLabel.split( '_' )[ 0 ] )
                    buttonName = buttonLabel[ buttonLabel.find( '_' )+1: ]
                    self.buttons[ buttonPosition ] = [ buttonName, buttonBitmap ]
                    
                except ValueError:
                    print 'Symbol %s ma nieprawidłową nazwę.' % ( buttonLabel )
                    pass

	#-------------------------------------------------------------------------
	def createGui(self):

		self.mainSizer = wx.BoxSizer( wx.VERTICAL )

		self.subSizer = wx.GridBagSizer( self.xBorder, self.yBorder )

		if self.control != 'tracker':
			event = eval('wx.EVT_LEFT_DOWN')
		else:
			event = eval('wx.EVT_BUTTON')
		
		for key, value in self.buttons.items( ):
			if key == 1 or key == 2 or key == 3 or key == 4:
				b = bt.GenBitmapButton( self, -1, name = value[ 0 ], bitmap = value[ 1 ] )
				b.SetBackgroundColour( self.backgroundColour )
				b.SetBezelWidth( 3 )
				b.Bind( event, self.onPress )
				
				self.subSizer.Add( b, ( ( key - 1 ) / self.numberOfColumns[ 0 ], ( key - 1 ) % self.numberOfColumns[ 0 ] ), wx.DefaultSpan, wx.EXPAND )

			elif key == 5:
				b = bt.GenBitmapButton( self, -1, name = value[ 0 ], bitmap = value[ 1 ] )
				b.SetBackgroundColour( self.backgroundColour )
				b.SetBezelWidth( 3 )
				b.Bind( event, self.onPress )

				self.subSizer.Add( b, ( ( key - 1 ) / self.numberOfColumns[ 0 ], ( key - 1 ) % self.numberOfColumns[ 0 ] ), ( 1, 2 ), wx.EXPAND )
			
			else:
				b = bt.GenBitmapButton( self, -1, name = value[ 0 ], bitmap = value[ 1 ] )
				b.SetBackgroundColour( self.backgroundColour )
				b.SetBezelWidth( 3 )
				b.Bind( event, self.onPress )
				
				self.subSizer.Add( b, ( ( key ) / self.numberOfColumns[ 0 ], ( key ) % self.numberOfColumns[ 0 ] ), wx.DefaultSpan, wx.EXPAND )
			
                for number in range( self.numberOfRows[ 0 ] ):
                    self.subSizer.AddGrowableRow( number )
                for number in range( self.numberOfColumns[ 0 ] ):
                    self.subSizer.AddGrowableCol( number )
		
		self. mainSizer.Add( self.subSizer, proportion = 1, flag = wx.EXPAND | wx.RIGHT | wx. LEFT | wx.TOP | wx.BOTTOM, border = self.xBorder )
		self.SetSizer( self. mainSizer )

	#-------------------------------------------------------------------------
	def initializeTimer(self):
		self.stoper = wx.Timer( self )
		self.Bind( wx.EVT_TIMER , self.timerUpdate , self.stoper )

		if self.control != 'tracker':
			self.stoper.Start( self.timeGap )
	
	#-------------------------------------------------------------------------
	def createBindings(self):
		self.Bind( wx.EVT_CLOSE , self.OnCloseWindow )

	#-------------------------------------------------------------------------
	def OnCloseWindow(self, event):

		if self.control != 'tracker':
			if True in [ 'debian' in item for item in os.uname( ) ]: #POSITION OF THE DIALOG WINDOW DEPENDS ON WINDOWS MANAGER NOT ON DESKTOP ENVIROMENT. THERE IS NO REASONABLE WAY TO CHECK IN PYTHON WHICH WINDOWS MANAGER IS CURRENTLY RUNNING, BESIDE IT IS POSSIBLE TO FEW WINDOWS MANAGER RUNNING AT THE SAME TIME. I DON'T SEE SOLUTION OF THIS ISSUE, EXCEPT OF CREATING OWN SIGNAL (AVR MICROCONTROLLERS).
				if os.environ.get('KDE_FULL_SESSION'):
					self.mousePosition = self.winWidth/1.05, self.winHeight/1.6
				# elif ___: #for gnome-debian
				# 	self.mousePosition = self.winWidth/6.5, self.winHeight/6.
				else:
					self.mousePosition = self.winWidth/1.07, self.winHeight/1.61
			else:
				self.mousePosition = self.winWidth/1.12, self.winHeight/1.6

		self.mouseCursor.move( *self.mousePosition )

		dial = wx.MessageDialog(self, 'Czy napewno chcesz wyjść z programu?', 'Wyjście',
					wx.YES_NO | wx.NO_DEFAULT | wx.ICON_QUESTION | wx.STAY_ON_TOP)
            
		ret = dial.ShowModal()
		
		if ret == wx.ID_YES:
			try:
				if "smplayer" in [psutil.Process(i).name() for i in psutil.pids( )]:
					os.system( 'smplayer -send-action quit' )
			except TypeError:
				if "smplayer" in [psutil.Process(i).name for i in psutil.pids( )]:
					os.system( 'smplayer -send-action quit' )

			try:
				self.parent.parent.parent.Destroy()
				self.parent.parent.Destroy()
				self.parent.Destroy()
				self.Destroy()

			except AttributeError:
				try:
					self.parent.parent.Destroy()
					self.parent.Destroy()
					self.Destroy()

				except AttributeError:
					try:		
						self.parent.Destroy()
						self.Destroy()

					except AttributeError:
						self.Destroy()

		else:
			event.Veto()

			if self.control != 'tracker':											
				self.mousePosition = self.winWidth - 8 - self.xBorder, self.winHeight - 16 - self.yBorder
				self.mouseCursor.move( *self.mousePosition )	

	#-------------------------------------------------------------------------
	def onExit(self):
		if __name__ == '__main__':
			self.stoper.Stop( )
			self.Destroy( )
		else:
			self.stoper.Stop( )
			self.MakeModal( False )
			self.parent.Show( True )
			if self.control == 'tracker':
				self.parent.stoper.Start( 0.15 * self.parent.timeGap )
			else:
				self.parent.stoper.Start( self.parent.timeGap )
				
			self.Destroy( )
				
        #-------------------------------------------------------------------------
        def onPress(self, event):

		if self.pressSound.lower( ) != 'off':
			self.pressingSound.play( )

		if self.control == 'tracker':
			if self.pressFlag == False:
				self.button = event.GetEventObject()
				self.button.SetBackgroundColour( self.selectionColour )
				self.pressFlag = True
				self.label = event.GetEventObject().GetName().encode( 'utf-8' )			
				self.stoper.Start( 0.15 * self.timeGap )

				if self.label == 'volume down':
					try:
						recentVolume = alsaaudio.Mixer( control = 'Master', cardindex = self.card_index ).getvolume( )[ 0 ] 
						alsaaudio.Mixer( control = 'Master', cardindex = self.card_index ).setvolume( recentVolume - 15, 0 )
						time.sleep( 1.5 )

					except alsaaudio.ALSAAudioError:
						self.button.SetBackgroundColour( 'red' )
						self.button.SetFocus( )

						self.Update( )
						time.sleep( 1.5 )

				elif self.label == 'volume up':
					try:
						recentVolume = alsaaudio.Mixer( control = 'Master', cardindex = self.card_index ).getvolume( )[ 0 ] 
						alsaaudio.Mixer( control = 'Master', cardindex = self.card_index ).setvolume( recentVolume + 15, 0 )
						time.sleep( 1.5 )

					except alsaaudio.ALSAAudioError:
						self.button.SetBackgroundColour( 'red' )
						self.button.SetFocus( )
							
						self.Update( )
						time.sleep( 1.5 )

				elif self.label == 'play pause':
					if self.pressedStopFlag == True:
						os.system( 'smplayer -send-action play' ) 
						self.pressedStopFlag = False
						
					else:
						os.system( 'smplayer -send-action pause' )
						
				elif self.label == 'stop':
					os.system( 'smplayer -send-action stop && smplayer -send-action stop %% smplayer -send-action fullcreen' )
					self.pressedStopFlag = True
					
				elif self.label == 'fast backward':
					os.system( 'smplayer -send-action pl_prev' )
					
				elif self.label == 'fast forward':
					os.system( 'smplayer -send-action pl_next' )
					
				elif self.label == 'backward':
					os.system( 'smplayer -send-action rewind1' )
					
				elif self.label == 'forward':
					os.system( 'smplayer -send-action forward1' )
					
				elif self.label == 'repeat':
					os.system( 'smplayer -send-action repeat' )
					
				elif self.label == 'playlist repeat':
					os.system( 'smplayer -send-action pl_repeat' )
					
				elif self.label == 'cancel':
					if "smplayer" in [psutil.Process(i).name() for i in psutil.pids( )]:
						os.system( 'smplayer -send-action quit' )
						
					self.onExit( )
					
				elif self.label == 'back':
					self.onExit( )
				
				elif self.label == 'playlist':
					os.system( 'smplayer -send-action show_playlist' )

		else:
			self.numberOfPresses += 1
			self.numberOfEmptyIteration = 0

			if self.numberOfPresses == 1:

				if self.flag == 'row':

                                        if self.pressSound == "voice":
                                                if (self.rowIteration == 1):
                                                        self.oneSound.play()
                                                if (self.rowIteration == 2):
                                                        self.twoSound.play()
                                                if (self.rowIteration == 4):
                                                        self.fourSound.play()
                                                if (self.rowIteration == 5):
                                                        self.fiveSound.play()
                                                if (self.rowIteration == 6):
                                                        self.sixSound.play()
                                                if (self.rowIteration == 7):
                                                        self.sevenSound.play()

					if self.rowIteration == 1 or self.rowIteration == 2:
						buttonsToHighlight = range( ( self.rowIteration - 1 ) * self.numberOfColumns[ 0 ], ( self.rowIteration - 1 ) * self.numberOfColumns[ 0 ] + self.numberOfColumns[ 0 ] )
						for button in buttonsToHighlight:
							item = self.subSizer.GetItem( button )
							b = item.GetWindow( )
							b.SetBackgroundColour( self.selectionColour )
							b.SetFocus( )
						self.flag = 'columns'
						self.colIteration = 0                                

					elif self.rowIteration == 3:
                                                if self.pressSound == "voice":
                                                        self.playlistSound.play()
						buttonsToHighlight = ( self.rowIteration - 1 ) * self.numberOfColumns[ 0 ],
						for button in buttonsToHighlight:
							item = self.subSizer.GetItem( button )
							b = item.GetWindow( )
							b.SetBackgroundColour( self.selectionColour )
							b.SetFocus( )

						self.rowIteration = 0
						os.system( 'smplayer -send-action show_playlist' )

					else:
						buttonsToHighlight = range( ( self.rowIteration - 1 ) * self.numberOfColumns[ 0 ] - 1, ( self.rowIteration - 1) * self.numberOfColumns[ 0 ] + self.numberOfColumns[ 0 ] - 1 )
						for button in buttonsToHighlight:
							item = self.subSizer.GetItem( button )
							b = item.GetWindow( )
							b.SetBackgroundColour( self.selectionColour )
							b.SetFocus( )
						self.flag = 'columns'
						self.colIteration = 0                                

				elif self.flag == 'columns':

					if self.rowIteration == 1 or self.rowIteration == 2:
						self.position = ( self.rowIteration - 1 ) * self.numberOfColumns[ 0 ] + self.colIteration

					else:
						self.position = ( self.rowIteration - 1 ) * self.numberOfColumns[ 0 ] + self.colIteration - 1

					item = self.subSizer.GetItem( self.position - 1 )
					selectedButton = item.GetWindow( )
					selectedButton.SetBackgroundColour( self.selectionColour )
					selectedButton.SetFocus( )

					self.Update( )

					if self.buttons[ self.position ][ 0 ] == 'volume down':
						try:
                                                        if self.pressSound == "voice":
                                                                self.ciszejSound.play()

                                                        
                                                        self.reader.readParameters()
                                                        parameters = self.reader.getParameters()
                                                        self.unpackParameters(parameters)
                                                        
                                                        if self.volumeLevel == 0: 
                                                                raise alsaaudio.ALSAAudioError
                                                        else:
                                                                for idx, item in enumerate(self.volumeLevels):
                                                                        if self.volumeLevel == item:
                                                                                self.volumeLevel = self.volumeLevels[idx-1]
                                                                                break

                                                        os.system("pactl set-sink-volume alsa_output.pci-0000_00_1b.0.analog-stereo %d%%" % self.volumeLevel)
                                                        self.reader.saveVolume(self.volumeLevel)
                                                        time.sleep( 1.5 )

						except alsaaudio.ALSAAudioError:
							selectedButton.SetBackgroundColour( 'red' )
							selectedButton.SetFocus( )

							self.Update( )
							time.sleep( 1.5 )

					elif self.buttons[ self.position ][ 0 ] == 'volume up':
						try:
                                                        if self.pressSound == "voice":
                                                                self.glosniejSound.play()

                                                        self.reader.readParameters()
                                                        parameters = self.reader.getParameters()
                                                        self.unpackParameters(parameters)
                                                        
                                                        if self.volumeLevel == 160: 
                                                                raise alsaaudio.ALSAAudioError
                                                        else:
                                                                for idx, item in enumerate(self.volumeLevels):
                                                                        if self.volumeLevel == item:
                                                                                self.volumeLevel = self.volumeLevels[idx+1]
                                                                                break
                                                                                        
                                                        os.system("pactl set-sink-volume alsa_output.pci-0000_00_1b.0.analog-stereo %d%%" % self.volumeLevel)
                                                        self.reader.saveVolume(self.volumeLevel)
                                                
                                                        time.sleep( 1.5 )
					

						except alsaaudio.ALSAAudioError:
							selectedButton.SetBackgroundColour( 'red' )
							selectedButton.SetFocus( )

							self.Update( )
							time.sleep( 1.5 )

					elif self.buttons[ self.position ][ 0 ] == 'play pause':
                                                if self.pressSound == "voice":
                                                        self.zatrzymajGrajSound.play()
						if self.pressedStopFlag == True:
							os.system( 'smplayer -send-action play' ) 
							self.pressedStopFlag = False

						else:
							os.system( 'smplayer -send-action pause' )

					elif self.buttons[ self.position ][ 0 ] == 'stop':
                                                if self.pressSound == "voice":
                                                        self.stopSound.play()
						os.system( 'smplayer -send-action stop && smplayer -send-action stop %% smplayer -send-action fullcreen' )
						self.pressedStopFlag = True

					elif self.buttons[ self.position ][ 0 ] == 'fast backward':
                                                if self.pressSound == "voice":
                                                        self.przewinDoTyluSzybkoSound.play()
						os.system( 'smplayer -send-action pl_prev' )

					elif self.buttons[ self.position ][ 0 ] == 'fast forward':
                                                if self.pressSound == "voice":
                                                        self.przewinDoPrzoduSzybkoSound.play()
						os.system( 'smplayer -send-action pl_next' )

					elif self.buttons[ self.position ][ 0 ] == 'backward':
                                                if self.pressSound == "voice":
                                                        self.przewinDoTyluSound.play()
						os.system( 'smplayer -send-action rewind1' )

					elif self.buttons[ self.position ][ 0 ] == 'forward':
                                                if self.pressSound == "voice":
                                                        self.przewinDoPrzoduSound.play()
						os.system( 'smplayer -send-action forward1' )

					elif self.buttons[ self.position ][ 0 ] == 'repeat':
                                                if self.pressSound == "voice":
                                                        self.powtarzajUtworSound.play()
						os.system( 'smplayer -send-action repeat' )

					elif self.buttons[ self.position ][ 0 ] == 'playlist repeat':
                                                if self.pressSound == "voice":
                                                        self.powtarzajListeSound.play()
						os.system( 'smplayer -send-action pl_repeat' )

					elif self.buttons[ self.position ][ 0 ] == 'cancel':
                                                if self.pressSound == "voice":
                                                        self.wyjscieSound.play()
						if "smplayer" in [psutil.Process(i).name() for i in psutil.pids( )]:
							os.system( 'smplayer -send-action quit' )

						self.onExit( )

					elif self.buttons[ self.position ][ 0 ] == 'back':
                                                if self.pressSound == 'voice':
                                                        self.powrotSound.play()
						self.onExit( )

					selectedButton.SetBackgroundColour( self.backgroundColour ) # depend on abilites comment or not
					self.flag = 'row'
					self.rowIteration = 0
					self.colIteration = 0
					self.countRows = 0
					self.countColumns = 0

			else:
				pass

			# print self.numberOfPresses

	#-------------------------------------------------------------------------
	def timerUpdate(self, event):

		if self.control == 'tracker':

			if self.button.GetBackgroundColour( ) == self.backgroundColour:
				self.button.SetBackgroundColour( self.selectionColour )
				
			else:
				self.button.SetBackgroundColour( self.backgroundColour )	

			self.stoper.Stop( )
			self.pressFlag = False

		else:
			if self.control != 'tracker':
				self.mouseCursor.move( *self.mousePosition )	

			self.numberOfPresses = 0

			if self.numberOfEmptyIteration < 3*0.9999999999:

				if self.switchSound.lower( ) == 'on':
					self.switchingSound.play( )

				if self.flag == 'row': #flag == row ie. switching between rows

						self.numberOfEmptyIteration += 1. / self.numberOfRows[ 0 ]

						self.rowIteration = self.rowIteration % self.numberOfRows[ 0 ]

                                                if self.switchSound == "voice":
                                                        if (self.rowIteration == 0):
                                                                self.oneSound.play()
                                                        if (self.rowIteration == 1):
                                                                self.twoSound.play()
                                                        if (self.rowIteration == 3):
                                                                self.fourSound.play()
                                                        if (self.rowIteration == 4):
                                                                self.fiveSound.play()
                                                        if (self.rowIteration == 5):
                                                                self.sixSound.play()
                                                        if (self.rowIteration == 6):
                                                                self.sevenSound.play()

						items = self.subSizer.GetChildren( )
						for item in items:
							b = item.GetWindow( )
							b.SetBackgroundColour( self.backgroundColour )
							b.SetFocus( )

						if self.rowIteration == 0 or self.rowIteration == 1:
							scope = range( self.rowIteration * self.numberOfColumns[ 0 ], self.rowIteration * self.numberOfColumns[ 0 ] + self.numberOfColumns[ 0 ] )

						elif self.rowIteration == 2:
                                                        if self.switchSound == "voice":
                                                                self.playlistSound.play()

							scope = self.rowIteration * self.numberOfColumns[ 0 ], 

						else:
							scope = range( self.rowIteration * self.numberOfColumns[ 0 ] - 1, self.rowIteration * self.numberOfColumns[ 0 ] + self.numberOfColumns[ 0 ] - 1 )
						for i in scope:
							item = self.subSizer.GetItem( i )
							b = item.GetWindow( )
							b.SetBackgroundColour( self.scanningColour )
							b.SetFocus( )

						self.rowIteration += 1

				elif self.flag == 'columns': #flag = columns ie. switching between cells in the particular row

					if self.countColumns == self.countMaxColumns:
						self.flag = 'row'
						self.rowIteration = 0
						self.colIteration = 0
						self.countColumns = 0
						self.countRows = 0

						items = self.subSizer.GetChildren( )
						for item in items:
							b = item.GetWindow( )
							b.SetBackgroundColour( self.backgroundColour )
							b.SetFocus( )

					else:
						self.colIteration = self.colIteration % self.numberOfColumns[ 0 ]

						if self.colIteration == self.numberOfColumns[ 0 ] - 1:
							self.countColumns += 1

						items = self.subSizer.GetChildren( )
						for item in items:
							b = item.GetWindow( )
							b.SetBackgroundColour( self.backgroundColour )
							b.SetFocus( )

						if self.rowIteration == 1 or self.rowIteration == 2:
							item = self.subSizer.GetItem( ( self.rowIteration - 1 ) * self.numberOfColumns[ 0 ] + self.colIteration )

						else:
							item = self.subSizer.GetItem( ( self.rowIteration - 1 ) * self.numberOfColumns[ 0 ] + self.colIteration - 1 )				
						b = item.GetWindow( )
						b.SetBackgroundColour( self.scanningColour )
						b.SetFocus( )
                                                logo = b.Name
                                                
                                                if self.switchSound == "voice":
                                                        if logo == 'volume down':
                                                                self.ciszejSound.play()
                                                        if logo == 'volume up':
                                                                self.glosniejSound.play()
                                                        if logo == 'play pause':
                                                                self.zatrzymajGrajSound.play()
                                                        if logo == 'stop':
                                                                self.stopSound.play()
                                                        if logo == 'fast backward':
                                                                self.przewinDoTyluSzybkoSound.play()
                                                        if logo == 'fast forward':
                                                                self.przewinDoPrzoduSzybkoSound.play()
                                                        if logo == 'backward':
                                                                self.przewinDoTyluSound.play()
                                                        if logo == 'forward':
                                                                self.przewinDoPrzoduSound.play()
                                                        if logo == 'repeat':
                                                                self.powtarzajUtworSound.play()
                                                        if logo == 'playlist repeat':
                                                                self.powtarzajListeSound.play()
                                                        if logo == 'cancel':
                                                                self.wyjscieSound.play()
                                                        if logo == 'back':
                                                                self.powrotSound.play()
                                                
						self.colIteration += 1

			else:
                            if self.switchSound == "voice":
                                    self.usypiamSound.play()
			    self.stoper.Stop( )
			    suspend.suspend( self, id = 2 ).Show( True )
			    self.Hide( )

			    items = self.subSizer.GetChildren( )			
			    for item in items:
				    b = item.GetWindow( )
				    b.SetBackgroundColour( self.backgroundColour )
				    b.SetFocus( )

			    self.numberOfEmptyIteration = 0
			    self.countColumns = 0
			    self.countRows = 0
			    self.colIteration = 0
			    self.rowIteration = 0
			    self.countColumns = 0
			    self.countRows = 0
			    self.numberOfPresses = 1
Example #49
0
class suspend( wx.Frame ):
	def __init__(self, parent, id):

	    self.winWidth, self.winHeight = wx.DisplaySize( )

            wx.Frame.__init__( self , parent , id, 'bookSuspend', size = ( 210, 280 ), pos = ( self.winWidth - 215, self.winHeight - 312 ) )

            style = self.GetWindowStyle( )
            self.SetWindowStyle( style | wx.STAY_ON_TOP )
            self.parent = parent

            self.MakeModal( True )
            
            self.initializeParameters( )            
            self.createGui( )
            self.initializeTimer( )
            self.createBindings( )						

	    self.Show( True )
	    self.SetTransparent( 0 )

	#-------------------------------------------------------------------------
	def initializeParameters(self):

            with open( '.pathToATPlatform' ,'r' ) as textFile:
		    self.pathToATPlatform = textFile.readline( )

	    with open( self.pathToATPlatform + 'parameters' ,'r' ) as parametersFile:
		    line = parametersFile.readline( )

		    try:
			    self.timeGap = int( line[ line.rfind( '=' ) + 2: -1 ] )
		    except ValueError:
		    	    print '\nNiewłaściwie opisany parametr. Błąd w linii:\n%s' % line
		    	    self.timeGap = 1500

            self.mouseCursor = PyMouse( )
	    self.mousePosition = self.winWidth - 8, self.winHeight - 8
            self.mouseCursor.move( *self.mousePosition )
	    
	    self.numberOfPresses = 3

	#-------------------------------------------------------------------------
	def createGui(self):

		self.mainSizer = wx.BoxSizer( wx.VERTICAL )

		self.subSizer = wx.GridBagSizer( 4, 4 )

                b = bt.GenButton( self, -1, '', name='' )
                b.Bind( wx.EVT_LEFT_DOWN, self.onPress )

                self.subSizer.Add( b, ( 0, 0 ), wx.DefaultSpan, wx.EXPAND )

                self.subSizer.AddGrowableRow( 0 )
                self.subSizer.AddGrowableCol( 0 )

		self. mainSizer.Add( self.subSizer, proportion = 1, flag = wx.EXPAND )
		self.SetSizer( self. mainSizer )

	#-------------------------------------------------------------------------
	def initializeTimer(self):
		self.stoper = wx.Timer( self )
		self.Bind( wx.EVT_TIMER , self.timerUpdate , self.stoper )
		self.stoper.Start( self.timeGap )

	#-------------------------------------------------------------------------
	def createBindings(self):
		self.Bind( wx.EVT_CLOSE, self.OnCloseWindow )

	#-------------------------------------------------------------------------
	def OnCloseWindow(self, event):

		self.mousePosition = self.winWidth/1.85, self.winHeight/1.85	
		self.mouseCursor.move( *self.mousePosition )	

		dial = wx.MessageDialog(None, 'Czy napewno chcesz wyjść z programu?', 'Wyjście',
					wx.YES_NO | wx.NO_DEFAULT | wx.ICON_QUESTION | wx.STAY_ON_TOP)
            
		ret = dial.ShowModal()
		
		if ret == wx.ID_YES:
			os.system( 'wmctrl -c Przeglądarka\ książek' )
			os.system( 'wmctrl -c E-book\ Viewer' )

			try:
				self.parent.parent.parent.Destroy()
				self.parent.parent.Destroy()
				self.parent.Destroy()
				self.Destroy()

			except AttributeError:
				try:
					self.parent.parent.Destroy()
					self.parent.Destroy()
					self.Destroy()

				except AttributeError:
					try:		
						self.parent.Destroy()
						self.Destroy()

					except AttributeError:
						self.Destroy()

		else:
			event.Veto()
			self.mousePosition = self.winWidth - 8, self.winHeight - 8
			self.mouseCursor.move( *self.mousePosition )	

	#-------------------------------------------------------------------------
	def onExit(self):
		if __name__ == '__main__':
			self.stoper.Stop( )
			self.Destroy( )
		else:
			self.stoper.Stop( )
			self.MakeModal( False )
			self.parent.Show( True )
			self.parent.stoper.Start( self.parent.timeGap )
			self.Destroy( )

	#-------------------------------------------------------------------------
        def onPress(self, event):
		
		self.stoper.Stop( )
		self.numberOfPresses += 1
		# print self.numberOfPresses

		if self.numberOfPresses == 1:
			self.suspendTime = time.time( )

			while True: 
				if time.time ( ) - self.suspendTime < 6:
					os.system( 'wid=`xdotool search --onlyvisible --name Przeglądarka\ książek` && xdotool windowfocus $wid && xdotool key --window $wid Page_Down' )
					os.system( 'wid=`xdotool search --onlyvisible --name E-book\ Viewer` && xdotool windowfocus $wid && xdotool key --window $wid Page_Down' )
					self.stoper.Start( self.timeGap )
					break

		elif self.numberOfPresses == 2:
			# if time.time( ) - self.suspendTime > 6:
			# 	self.stoper.Start( self.timeGap )
			# 	os.system( 'wid=`xdotool search --onlyvisible --name Przeglądarka\ książek` && xdotool windowfocus $wid && xdotool key --window $wid Page_Down' )
			# 	self.stoper.Start( self.timeGap )
			
			# else:
			bookPilot.pilot( self, id = 2 ).Show( True )
			self.Hide( )
	
		else:
			pass
		
	#-------------------------------------------------------------------------
	def timerUpdate(self, event):
		
               	self.mouseCursor.move( *self.mousePosition )
		self.numberOfPresses = 0
"""
Stream Pupil gaze coordinate data using zmq to control a mouse with your eye.
Please note that marker tracking must be enabled, and in this example we have named the surface "screen."
You can name the surface what you like in Pupil capture and then write the name of the surface you'd like to use on line 17.
"""

import zmq
from msgpack import loads
import subprocess as sp
from platform import system

try:
    # not working on MacOS
    from pymouse import PyMouse
    m = PyMouse()
    m.move(0, 0)  # hack to init PyMouse -- still needed
except ImportError:
    pass


def set_mouse(x=0, y=0, click=0):
    if system() == "Darwin":
        sp.Popen([
            "./mac_os_helpers/mouse", "-x",
            str(x), "-y",
            str(y), "-click",
            str(click)
        ])
    else:
        if click:
            m.click(x, y)
Example #51
0
from pymouse import PyMouse
import time

# instantiate an mouse object


m = PyMouse()

# move the mouse to int x and int y (these are absolute positions)
## m.move(200, 200)
# click works about the same, except for int button possible values are 1: left, 2: right, 3: middle
print m.position()
Example #52
0
import numpy as np
import cv2
from pymouse import PyMouse

if __name__ == '__main__':
    m = PyMouse()
    #print m.shape()

    cap = cv2.VideoCapture(0)  #video record code
    facedata = "haarcascade_frontalface_default.xml"  #process code
    eyedata = "haarcascade_eye.xml"
    cascade = cv2.CascadeClassifier(facedata)
    cascade2 = cv2.CascadeClassifier(eyedata)
    ret, frame = cap.read()
    print cap.get(3), cap.get(4), "<-dimensions"

    while (ret):  #record code
        img = cv2.imread("123.jpg")
        img = frame

        minisize = (img.shape[1], img.shape[0])  #video code
        miniframe = cv2.resize(img, minisize)

        faces = cascade.detectMultiScale(miniframe)
        ex = ey = eh = ew = 0
        #print "faces_len, face[0]_len", type(faces), type(faces[0])

        for f in faces:

            x, y, w, h = [v for v in f]
Example #53
0
class KeyboardControl(PyKeyboardEvent):
    """
    This class is used to generate demonstrations from human through keyboard.
    Some tricks are used to make the keyboard controlling more user friendly.
    Move the agent around by key "W, A, S, D" and open or close gripper by
    key "E", and move the robot arm joints (if there is) by mouse and key "R, F".
    """
    def __init__(self):
        super().__init__(capture=False)
        self._mouse = PyMouse()
        x, y = self._mouse.screen_size()
        self._x_center, self._y_center = x / 2.0, y / 2.0
        self._speed = 0
        self._turning = 0
        self._arm_joints = [0, 0, 0]
        self._gripper_open = True
        self._wheel_step = 0.5
        self._speed_decay = 0.9
        self._turning_decay = 0.6
        self._done = False
        logging.info("Control:" + """
        W       : increase forward speed
        S       : increase backward speed
        A       : turn left
        D       : turn right
        E       : open/close gripper (if there is one)
        R/F     : move robot arm joint (if there is one)
        +       : increase the step size for W/S/A/D
        -       + decrease the step size for W/S/A/D
        Q       : quit
        mouse   : gripper position (if there is one)
        """)
        self.start()

    def reset(self):
        self._arm_joints = [0, 0, 0]
        self._gripper_open = True
        self._speed = 0
        self._turning = 0

    def get_agent_actions(self, agent_type):
        """
        Args:
            agent_type(sting): the agent type
        Returns:
            actions generated by the keyboard accroding to agent type
        """
        # decay the speed
        self._speed *= self._speed_decay
        self._turning *= self._turning_decay
        # get gripper pos
        mouse_x, mouse_y = self._get_mouse_pos()
        self._arm_joints[0] = mouse_x
        self._arm_joints[1] = mouse_y

        return self._convert_to_agent_action(agent_type)

    def tap(self, keycode, character, press):
        """ Keyboard event handler.

        Args:
            keycode(int): the key code
            character(string): the key name
            press(bool): True if the key was pressed and False if the key was released.
        """
        if not press:
            return
        if character == "w":
            self._speed = 0 if self._speed < -0.01 else self._speed + self._wheel_step
        elif character == "s":
            self._speed = 0 if self._speed > 0.01 else self._speed - self._wheel_step
        elif character == "a":
            self._turning = 0 if self._turning > 0.01 else self._turning - self._wheel_step
        elif character == "d":
            self._turning = 0 if self._turning < -0.01 else self._turning + self._wheel_step
        # arm_joint[2]
        elif character == "r":
            self._arm_joints[2] -= 0.1
        elif character == "f":
            self._arm_joints[2] += 0.1
        # gripper finger
        elif character == "e":
            self._gripper_open = not self._gripper_open
        # set step size
        elif character == "+":
            self._wheel_step *= 1.5
        elif character == "-":
            self._wheel_step *= 0.7
        elif character == "q":
            self._done = True

    def is_done(self):
        return self._done

    def _get_mouse_pos(self):
        """ Get the mouse position and normalize to (-1, 1).
        """
        x, y = self._mouse.position()
        x, y = x / self._x_center - 1.0, y / self._y_center - 1.0
        return x, y

    def _convert_to_agent_action(self, agent_type):
        if agent_type == 'pioneer2dx_noplugin' or agent_type == 'turtlebot':
            actions = self._to_diff_drive_action()
        elif agent_type == 'youbot_noplugin':
            actions = self._to_youbot_action()
        elif agent_type == 'pr2_noplugin':
            actions = self._to_pr2_action()
        elif agent_type == 'kuka_lwr_4plus':
            actions = self._to_lwr4_action()
        else:
            actions = []
            logging.info("agent type not supported yet: " + agent_type)
        return actions

    def _to_diff_drive_action(self):
        left_wheel_joint = self._speed + self._turning
        right_wheel_joint = self._speed - self._turning
        actions = [left_wheel_joint, right_wheel_joint]
        return actions

    def _to_youbot_action(self):
        """ Convert to the wrapped youbot actions
        """
        if self._gripper_open:
            finger_joint = 0.5
        else:
            finger_joint = -0.5
        actions = [
            self._arm_joints[0], self._arm_joints[1], self._arm_joints[2], 0,
            finger_joint, self._speed, self._turning
        ]
        return actions

    def _to_lwr4_action(self):
        actions = [
            self._speed, self._turning, self._arm_joints[0],
            self._arm_joints[1], self._arm_joints[2]
        ]
        return actions

    def _to_pr2_action(self):
        wheel_joint_bl = self._speed + self._turning
        wheel_joint_br = self._speed - self._turning
        wheel_joint_fl = self._speed + self._turning
        wheel_joint_fr = self._speed - self._turning
        actions = [
            wheel_joint_fl, wheel_joint_fl, wheel_joint_fr, wheel_joint_fr,
            wheel_joint_bl, wheel_joint_bl, wheel_joint_br, wheel_joint_br
        ]
        return actions
Example #54
0
#-*- coding:utf-8 -*-
import pyscreenshot as ImageGrab
#import cv2 as cv
from PIL import Image
import math
import operator
from functools import reduce
import time
from pymouse import PyMouse
from pykeyboard import PyKeyboard

m = PyMouse()
k = PyKeyboard()
x,y = m.screen_size()
results = []

def image_contrast(img1, img2):

    image1 = Image.open(img1)
    image2 = Image.open(img2)

    h1 = image1.histogram()
    h2 = image2.histogram()

    result = math.sqrt(reduce(operator.add,  list(map(lambda a,b: (a-b)**2, h1, h2)))/len(h1) )

    return result

def game_HookUp():
    m.click(x//2,y//2,1)
def main():
    global Icq1List
    global Icq2List
    global PAcurrentList
    # 配置线损
    lossName = PM.query("CONFigure:BASE:FDCorrection:CTABle:CATalog?")
    time.sleep(1)
    if lossName.find("CMW_loss") != -1:
        PM.write("CONFigure:BASE:FDCorrection:CTABle:DELete 'CMW_loss'")
    PM.write(
        "CONFigure:BASE:FDCorrection:CTABle:CREate 'CMW_loss', 1920000000, 0.8, 1980000000, 0.8, \
             2110000000, 0.8, 2170000000, 0.8, 1850000000, 0.8 1910000000, 0.8, 1930000000, 0.8, 1990000000, 0.8,\
             824000000, 0.5, 849000000, 0.5, 869000000, 0.5, 894000000, 0.5, 925000000, 0.5, 960000000, 0.5, \
             880000000, 0.5, 915000000, 0.5, 2350000000, 0.9, 2535000000, 0.9, 2593000000, 0.9"
    )
    PM.write("CONFigure:FDCorrection:ACTivate RF1C, 'CMW_loss', RXTX, RF1"
             )  #配置RF1 Common口的Tx Rx方向损耗
    PM.write("CONFigure:FDCorrection:ACTivate RF1O, 'CMW_loss', TX, RF1"
             )  #配置RF1 OUT口的Tx方向损耗

    if PAcurrentGenerateMode == 0:
        Icq1 = int(PAcurrentInitial / 256)
        Icq2 = int(PAcurrentInitial - Icq1 * 256)
        Icq1List = []
        Icq2List = []
        for ii in range(-LeftExtendPeriodIcq1, RightExtendPeriodIcq1 + 1):
            Temp_Icq1 = list(
                range(Icq1 + ii * period - ScanRangeIcq1,
                      Icq1 + ii * period + ScanRangeIcq1 + 1))
            Icq1List.extend(Temp_Icq1)
        for ii in range(-LeftExtendPeriodIcq2, RightExtendPeriodIcq2 + 1):
            Temp_Icq2 = list(
                range(Icq2 + ii * period - ScanRangeIcq2,
                      Icq2 + ii * period + ScanRangeIcq2 + 1))
            Icq2List.extend(Temp_Icq2)
    if PAcurrentGenerateMode < 2:
        PAcurrentList = zeros(len(Icq1List) * len(Icq2List))
        for ii in range(len(Icq1List)):
            for jj in range(len(Icq2List)):
                PAcurrentList[ii + jj * len(Icq1List)] = (Icq1List[ii] * 256 +
                                                          Icq2List[jj])
        PAcurrentList = list(map(int, PAcurrentList))
        print("Icq1List is %s" % Icq1List)
        print("Icq2List is %s" % Icq2List)
    if PAcurrentListExtendFlag == 1:
        PAcurrentList.extend(PAcurrentListExtend)
    print("PAcurrentList length is %d" % (len(PAcurrentList)))
    print("PAcurrentList is %s" % PAcurrentList)

    if ModeChosen in [0, 1]:
        ChannelList = channelLteList(bandChosen, LteBW, ScanType)
    elif ModeChosen == 2:
        ChannelList = channel3GList(bandChosen, ScanType)
    if ReadCurrentFlag == 0:
        print("expected test time is %3.1f minutes" % float(
            len(PAcurrentList) * len(RGIlist) * len(ChannelList) * 16 / 60))
    else:
        print("Reading current needed, expected test time is %3.1f minutes" %
              float(len(PAcurrentList) * len(RGIlist) * len(ChannelList)))

#########################   获取各个控件的位置     ##########################################
#########################   测试过程中请不要操作鼠标和键盘     ###############################
    mouse = PyMouse()
    key = PyKeyboard()
    input("Move mouse to 'Tear Down' then press Enter")
    (IsTearDownX, IsTearDownY) = mouse.position()  #获取当前坐标的位置
    print(IsTearDownX, IsTearDownY)
    input("Move mouse to 'Tx Channel' then press Enter")
    (TxChannelX, TxChannelY) = mouse.position()  #获取当前坐标的位置
    print(TxChannelX, TxChannelY)
    input("Move mouse to 'Set Radio Config' then press Enter")
    (SetRadioConfigX, SetRadioConfigY) = mouse.position()  #获取当前坐标的位置
    print(SetRadioConfigX, SetRadioConfigY)
    input("Move mouse to 'RGI' then press Enter")
    (RGIx, RGIy) = mouse.position()  #获取当前坐标的位置
    print(RGIx, RGIy)
    input("Move mouse to 'PA current' then press Enter")
    (PAcurrentX, PAcurrentY) = mouse.position()  #获取当前坐标的位置
    print(PAcurrentX, PAcurrentY)
    input("Move mouse to 'Tx Override' then press Enter")
    (TxOverrideX, TxOverrideY) = mouse.position()  #获取当前坐标的位置
    print(TxOverrideX, TxOverrideY)
    #########################   获取各个控件的位置     ##########################################
    #########################   测试过程中请不要操作鼠标和键盘     ###############################

    TimeStart = time.clock()
    print("test start. Please check instrument parameters")
    interpolateTemp = numpy.zeros([len(RGIlist), 4])  #用来做拟合/插值,便于比较

    for ii in range(len(bandChosen)):
        if ModeChosen == 0:
            PMwrite(PM, "CONFigure:LTE:MEAS:DMODe FDD")
        elif ModeChosen == 1:
            PMwrite(PM, "CONFigure:LTE:MEAS:DMODe TDD")
        if ModeChosen in [0, 1]:
            PMwrite(PM, "ROUTe:LTE:MEAS:SCENario:SALone RF1C, RX1")
            PMwrite(PM, "CONFigure:LTE:MEAS:BAND %s" % bandChosen[ii])
            PMwrite(
                PM, "CONFigure:LTE:MEAS:RFSettings:PCC:FREQuency %dCH" %
                ChannelList[ii][0])
            PMwrite(PM, "CONFigure:LTE:MEAS:MEValuation:REPetition SINGleshot")
            PMwrite(PM, "CONFigure:LTE:MEAS:MEValuation:MSUBframes 0, 10, 2")
            PMwrite(PM, "CONFigure:LTE:MEAS:PCC:CBANdwidth %s" % LteBW)
            PMwrite(
                PM,
                "TRIGger:LTE:MEAS:MEValuation:SOURce 'Free Run (Fast Sync)'")
            PMwrite(PM, "CONFigure:LTE:MEAS:RFSettings:ENPMode MANual")
            PMwrite(PM, "CONFigure:LTE:MEAS:RFSettings:ENPower 24")
            PMwrite(PM, "CONFigure:LTE:MEAS:RFSettings:UMARgin 12")
            PMwrite(PM, "CONFigure:LTE:MEAS:MEValuation:MOEXception ON")
        elif ModeChosen == 2:
            PMwrite(PM, "ROUTe:WCDMa:MEAS:SCENario:SALone RF1C, RX1")
            PMwrite(PM, "CONFigure:WCDMa:MEAS:BAND %s" % bandChosen[ii])
            PMwrite(
                PM, "CONFigure:WCDMa:MEAS:RFSettings:FREQuency %d CH" %
                ChannelList[ii][0])
            PMwrite(PM,
                    "CONFigure:WCDMa:MEAS:MEValuation:REPetition SINGleshot")
            PMwrite(PM,
                    "CONFigure:WCDMa:MEAS:MEValuation:SCOunt:MODulation 10")
            PMwrite(PM, "CONFigure:WCDMa:MEAS:MEValuation:SCOunt:SPECtrum 10")
            PMwrite(PM, "CONFigure:WCDMa:MEAS:MEValuation:MOEXception ON")
            PMwrite(
                PM,
                "TRIGger:WCDMa:MEAS:MEValuation:SOURce 'Free Run (Fast Sync)'")
            PMwrite(PM, "CONFigure:WCDMA:MEAS:RFSettings:ENPower 24")
            PMwrite(PM, "CONFigure:WCDMA:MEAS:RFSettings:UMARgin 12")
        os.system("pause")

        time.sleep(1)
        for jj in range(len(ChannelList[ii])):
            mouse.click(IsTearDownX, IsTearDownY, 1)
            mouse.click(SetRadioConfigX, SetRadioConfigY, 1)
            time.sleep(3)
            mouse.click(IsTearDownX, IsTearDownY, 1)
            mouse.click(TxChannelX, TxChannelY, 1, 2)
            key.type_string(str(ChannelList[ii][jj]))
            mouse.click(SetRadioConfigX, SetRadioConfigY, 1)
            time.sleep(0.2)

            if ModeChosen in [0, 1]:
                PMwrite(
                    PM, "CONFigure:LTE:MEAS:RFSettings:PCC:FREQuency %dCH" %
                    ChannelList[ii][jj])
            elif ModeChosen == 2:
                PMwrite(
                    PM, "CONFigure:WCDMa:MEAS:RFSettings:FREQuency %d CH" %
                    ChannelList[ii][jj])
            time.sleep(1)

            for kk in range(len(PAcurrentList)):
                mouse.click(PAcurrentX, PAcurrentY, 1, 2)
                key.type_string(str(PAcurrentList[kk]))
                time.sleep(0.2)
                Icqq1 = numpy.floor(PAcurrentList[kk] / 256)
                Icqq2 = PAcurrentList[kk] - Icqq1 * 256
                TestFlag = 1
                for ll in range(len(RGIlist)):
                    mouse.click(RGIx, RGIy, 1, 2)
                    key.type_string(str(RGIlist[ll]))
                    time.sleep(0.1)
                    mouse.click(TxOverrideX, TxOverrideY, 1)
                    time.sleep(0.1)

                    try:
                        if ModeChosen in [0, 1]:
                            PM.write("ABORt:LTE:MEAS:MEValuation")
                            PM.write("INIT:LTE:MEAS:MEValuation")
                            time.sleep(0.7)
                            LteAclr = PMquery(
                                PM, "FETCh:LTE:MEAS:MEValuation:ACLR:AVERage?"
                            )  #读取UE发射功率
                            LteAclrList = list(map(float, LteAclr.split(',')))
                            UEPwr = LteAclrList[4]
                            ChPwr = LteAclrList[4]
                            AdjCLRn = LteAclrList[3]
                            AdjCLRp = LteAclrList[5]
                        elif ModeChosen == 2:
                            PMwrite(PM, "ABORt:WCDMa:MEAS:MEValuation")
                            WAclrList = PMqueryWithDelay(
                                PM,
                                "READ:WCDMa:MEAS:MEValuation:SPECtrum:AVERage?"
                            ).split(',')
                            UEPwr = float(WAclrList[15])
                            ChPwr = float(WAclrList[1])
                            AdjCLRn = ChPwr - float(WAclrList[3])
                            AdjCLRp = ChPwr - float(WAclrList[4])
                    except Exception:
                        print("TxPwr underdriven or overdriven, ignored")
                        TestFlag = -1
                        break
                    if (AdjCLRn < 30 and ChPwr < 23):
                        print("ACLR too bad, ignored")
                        TestFlag = 0
                        break

                    if TestFlag == 1:
                        interpolateTemp[ll][0] = AdjCLRn
                        interpolateTemp[ll][1] = ChPwr
                        interpolateTemp[ll][2] = AdjCLRp
                        if ReadCurrentFlag == 1:
                            if ReadCurrentWaitTime == "Manual":
                                os.system("pause")
                            else:
                                time.sleep(int(ReadCurrentWaitTime))
                            if ModeChosen == 1:
                                CurrentLength = 40
                            else:
                                CurrentLength = 15
                            Current = numpy.zeros(CurrentLength)
                            for k in range(CurrentLength):
                                Current[k] = float(
                                    PMquery(PM_DCsupply, "MEASure:CURRent?"))
                                print(Current[k])
                                time.sleep(0.1 + numpy.random.rand() * 0.3)
                            if ModeChosen == 1:
                                temp_current = sorted(Current)
                                interpolateTemp[ll][3] = average(
                                    temp_current[2:(CurrentLength - 2)])
                            else:
                                interpolateTemp[ll][3] = average(Current)
                        else:
                            interpolateTemp[ll][3] = 0.001
                        print("%-4s %d %s %s %3d %3d %3.2f %3.2f %3.2f %1.3f" %(bandChosen[ii], ChannelList[ii][jj],\
                            RGIlist[ll],PAcurrentList[kk],Icqq1, Icqq2, AdjCLRn,ChPwr,AdjCLRp,interpolateTemp[ll][3]))

                    elif TestFlag == -1:
                        print("%-4s %d %s %s %3d %3d underdriven or overdriven, ignored" %(bandChosen[ii], ChannelList[ii][jj],\
                            RGIlist[ll],PAcurrentList[kk],Icqq1, Icqq2))
                    else:
                        print("%-4s %d %s %s %3d %3d ACLR too bad, ignored" %(bandChosen[ii], ChannelList[ii][jj],\
                            RGIlist[ll],PAcurrentList[kk],Icqq1, Icqq2))

                if TestFlag == 1:
                    Tmp1 = numpy.polyfit(interpolateTemp[:, 1],
                                         interpolateTemp[:, 0],
                                         len(RGIlist) - 1)
                    Tmp2 = numpy.polyfit(interpolateTemp[:, 1],
                                         interpolateTemp[:, 2],
                                         len(RGIlist) - 1)
                    Tmp3 = numpy.polyfit(interpolateTemp[:, 1],
                                         interpolateTemp[:, 3],
                                         len(RGIlist) - 1)
                    interpolateAclrLeft = numpy.polyval(Tmp1, IpNP)
                    interpolateAclrRight = numpy.polyval(Tmp2, IpNP)
                    interpolateCurrent = numpy.polyval(Tmp3, IpNP)
                    print("%-4s %d -- %s %3d %3d %3.2f %3.1f %3.2f %1.3f" %(bandChosen[ii], ChannelList[ii][jj],\
                        PAcurrentList[kk],Icqq1, Icqq2, interpolateAclrLeft,IpNP,interpolateAclrRight, interpolateCurrent))
                    LogfileWrite(LogFile, "%-4s %d -- %s %3d %3d %3.2f %3.1f %3.2f %1.3f\n" %(bandChosen[ii], ChannelList[ii][jj],\
                        PAcurrentList[kk],Icqq1, Icqq2, interpolateAclrLeft,IpNP,interpolateAclrRight, interpolateCurrent))
                elif TestFlag == -1:
                    print("%-4s %d -- %s %3d %3d --   %3.1f   --" %(bandChosen[ii], ChannelList[ii][jj],\
                        PAcurrentList[kk],Icqq1, Icqq2, IpNP))
                    LogfileWrite(LogFile, "%-4s %d -- %s %3d %3d --   %3.1f   --\n" %(bandChosen[ii], ChannelList[ii][jj],\
                        PAcurrentList[kk],Icqq1, Icqq2, IpNP))
                else:
                    print("%-4s %d -- %s %3d %3d bad  %3.1f  bad" %(bandChosen[ii], ChannelList[ii][jj],\
                        PAcurrentList[kk],Icqq1, Icqq2, IpNP))
                    LogfileWrite(LogFile, "%-4s %d -- %s %3d %3d bad  %3.1f  bad\n" %(bandChosen[ii], ChannelList[ii][jj],\
                        PAcurrentList[kk],Icqq1, Icqq2, IpNP))


############################## All test end  ##########################
    TimeEnd = time.clock()
    print("The total test time is %.1f minutes" % ((TimeEnd - TimeStart) / 60))
    endtime = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))
    print("Test finished at %s" % endtime)
    LogfileWrite(LogFile, "Test finished at %s\n\n" % endtime)
Example #56
0
class pilot(wx.Frame):
    def __init__(self, parent, id):

        self.winWidth, self.winHeight = wx.DisplaySize()

        self.dw, self.dh = wx.DisplaySize()

        self.initializeParameters()
        wx.Frame.__init__(self,
                          parent,
                          id,
                          'Pilot',
                          size=(220, 400),
                          pos=(self.dw - 230, self.dh - 435))
        self.SetBackgroundColour('black')

        style = self.GetWindowStyle()
        self.SetWindowStyle(style | wx.STAY_ON_TOP)
        self.parent = parent

        self.MakeModal(True)

        self.initializeBitmaps()
        self.createGui()
        self.createBindings()

        self.initializeTimer()

    #-------------------------------------------------------------------------
    def initializeParameters(self):

        with open('./.pathToAP', 'r') as textFile:
            self.pathToAP = textFile.readline()

        sys.path.append(self.pathToAP)
        from reader import reader

        self.reader = reader()
        self.reader.readParameters()
        parameters = self.reader.getParameters()
        self.unpackParameters(parameters)

        self.flag = 'row'
        self.pressFlag = False
        self.pressedStopFlag = False

        self.rowIteration = 0
        self.colIteration = 0

        self.rowIteration = 0
        self.colIteration = 0

        self.numberOfColumns = 2,
        self.numberOfRows = 5,

        self.numberOfSymbol = 0

        self.numberOfEmptyIteration = 0
        self.countRows = 0
        self.countColumns = 0
        self.button = 1
        self.countMaxRows = 2
        self.countMaxColumns = 2
        self.numberOfPresses = 0

        self.volumeLevels = [0, 20, 40, 60, 80, 100, 120, 140, 160]
        if self.volumeLevel not in self.volumeLevels:
            raise (
                "Wrong value of volumeLevel. Accepted values: 0, 20, 40, 60, 80, 100, 120, 140, 160"
            )

        ### if download option was available
    # self.youtubeFiles = sorted( glob.glob('./youtube playlist/*') )
    # if bool( self.youtubeFiles ) == False:
    #         self.lastYoutubeFile = 1
    # else:
    #         self.lastYoutubeFile = self.youtubeFiles[-1]

        if self.control != 'tracker':
            self.mouseCursor = PyMouse()
            # self.mousePosition = self.winWidth - 8 - self.xBorder, self.winHeight - 16 - self.yBorder
            # self.mouseCursor.move( *self.mousePosition )
            self.mouseCursor.move(self.dw - 225, self.dh - 265)

        if self.switchSound.lower() != 'off' or self.pressSound.lower(
        ) != 'off':
            mixer.init()
            self.switchingSound = mixer.Sound(self.pathToAP +
                                              '/sounds/switchSound.ogg')
            self.pressingSound = mixer.Sound(self.pathToAP +
                                             '/sounds/pressSound.ogg')

            self.ciszejSound = mixer.Sound(self.pathToAP +
                                           '/sounds/ciszej.ogg')
            self.glosniejSound = mixer.Sound(self.pathToAP +
                                             '/sounds/glosniej.ogg')

            self.nastepnySound = mixer.Sound(self.pathToAP +
                                             '/sounds/następny.ogg')
            self.poprzedniSound = mixer.Sound(self.pathToAP +
                                              '/sounds/poprzedni.ogg')

            self.zatrzymajGrajSound = mixer.Sound(self.pathToAP +
                                                  '/sounds/zatrzymaj_graj.ogg')
            self.pelnyEkranSound = mixer.Sound(self.pathToAP +
                                               '/sounds/pełny_ekran.ogg')

            self.wyjscieSound = mixer.Sound(self.pathToAP +
                                            '/sounds/wyjście.ogg')
            self.powrotSound = mixer.Sound(self.pathToAP +
                                           '/sounds/powrot.ogg')
            self.usypiamSound = mixer.Sound(self.pathToAP +
                                            '/sounds/usypiam.ogg')

            self.oneSound = mixer.Sound(self.pathToAP + '/sounds/rows/1.ogg')
            self.twoSound = mixer.Sound(self.pathToAP + '/sounds/rows/2.ogg')
            self.threeSound = mixer.Sound(self.pathToAP + '/sounds/rows/3.ogg')
            self.fourSound = mixer.Sound(self.pathToAP + '/sounds/rows/4.ogg')
            self.fiveSound = mixer.Sound(self.pathToAP + '/sounds/rows/5.ogg')

        self.width = self.numberOfColumns[0] * 120
        self.height = self.numberOfRows[0] * 100

    #-------------------------------------------------------------------------

    def unpackParameters(self, parameters):
        for item in parameters:
            try:
                setattr(self, item[:item.find('=')],
                        int(item[item.find('=') + 1:]))
            except ValueError:
                setattr(self, item[:item.find('=')], item[item.find('=') + 1:])

    #-------------------------------------------------------------------------
    def initializeBitmaps(self):

        radioLogoPaths = glob.glob(self.pathToAP +
                                   'icons/pilots/minitubePilot/*')  #labelFiles

        self.radios = {}

        for radioLogoPath in radioLogoPaths:

            radioLogoBitmap = wx.BitmapFromImage(
                wx.ImageFromStream(open(radioLogoPath, "rb")))

            radioLabel = radioLogoPath[radioLogoPath.rfind('/') +
                                       1:radioLogoPath.rfind('.')]
            try:
                radioPosition = int(radioLabel.split('_')[0])
                radioName = radioLabel[radioLabel.find('_') + 1:]
                self.radios[radioPosition] = [radioName, radioLogoBitmap]

            except ValueError:
                print 'Symbol %s w folderze %s ma nieprawidłową nazwę.' % (
                    symbolName.split('_')[0], page[page.rfind('/') + 1:])
                pass

    #-------------------------------------------------------------------------
    def createGui(self):

        self.mainSizer = wx.BoxSizer(wx.VERTICAL)

        self.subSizer = wx.GridBagSizer(4, 4)

        # print self.radios.keys()[-5:]

        for key, value in self.radios.items():
            if key == 1 or key == 2 or key == 3 or key == 4:
                b = bt.GenBitmapButton(self,
                                       -1,
                                       name=value[0],
                                       bitmap=value[1])
                b.SetBackgroundColour(self.backgroundColour)
                b.SetBezelWidth(3)
                b.Bind(wx.EVT_LEFT_DOWN, self.onPress)

                self.subSizer.Add(b, ((key - 1) / self.numberOfColumns[0],
                                      (key - 1) % self.numberOfColumns[0]),
                                  wx.DefaultSpan, wx.EXPAND)

            elif key == 5:
                b = bt.GenBitmapButton(self,
                                       -1,
                                       name=value[0],
                                       bitmap=value[1])
                b.SetBackgroundColour(self.backgroundColour)
                b.SetBezelWidth(3)
                b.Bind(wx.EVT_LEFT_DOWN, self.onPress)

                self.subSizer.Add(b, ((key - 1) / self.numberOfColumns[0],
                                      (key - 1) % self.numberOfColumns[0]),
                                  (1, 2), wx.EXPAND)

            elif key == 6:
                b = bt.GenBitmapButton(self,
                                       -1,
                                       name=value[0],
                                       bitmap=value[1])
                b.SetBackgroundColour(self.backgroundColour)
                b.SetBezelWidth(3)
                b.Bind(wx.EVT_LEFT_DOWN, self.onPress)

                self.subSizer.Add(b, ((key) / self.numberOfColumns[0],
                                      (key) % self.numberOfColumns[0]), (1, 2),
                                  wx.EXPAND)

            # elif key == 7 or key == 8:
            # 	b = bt.GenBitmapButton( self, -1, name = value[0], bitmap = value[1] )
            # 	b.SetBackgroundColour( self.backgroundColour )
            # 	b.SetBezelWidth( 3 )
            # 	b.Bind( wx.EVT_LEFT_DOWN, self.onPress )

            # 	self.subSizer.Add(b, ( (key+1) / self.numberOfColumns[0], (key+1) % self.numberOfColumns[0] ), wx.DefaultSpan, wx.EXPAND)

            elif key == 9 or key == 10:
                b = bt.GenBitmapButton(self,
                                       -1,
                                       name=value[0],
                                       bitmap=value[1])
                b.SetBackgroundColour(self.backgroundColour)
                b.SetBezelWidth(3)
                b.Bind(wx.EVT_LEFT_DOWN, self.onPress)

                self.subSizer.Add(b, ((key - 1) / self.numberOfColumns[0],
                                      (key - 1) % self.numberOfColumns[0]),
                                  wx.DefaultSpan, wx.EXPAND)

        for number in range(self.numberOfRows[0]):
            self.subSizer.AddGrowableRow(number)
        for number in range(self.numberOfColumns[0]):
            self.subSizer.AddGrowableCol(number)

        self.mainSizer.Add(self.subSizer, proportion=1, flag=wx.EXPAND)
        self.SetSizer(self.mainSizer)

    #-------------------------------------------------------------------------
    def initializeTimer(self):
        self.stoper = wx.Timer(self)
        self.Bind(wx.EVT_TIMER, self.timerUpdate, self.stoper)
        self.stoper.Start(self.timeGap)

    #-------------------------------------------------------------------------
    def createBindings(self):
        self.Bind(wx.EVT_CLOSE, self.OnCloseWindow)

    #-------------------------------------------------------------------------
    def OnCloseWindow(self, event):
        self.stoper.Stop()
        self.Destroy()

    #-------------------------------------------------------------------------
    def onExit(self):
        if __name__ == '__main__':
            self.stoper.Stop()
            self.Destroy()
        else:
            self.stoper.Stop()
            self.MakeModal(False)
            self.parent.Show(True)
            if self.control == 'tracker':
                self.parent.stoper.Start(0.15 * self.parent.timeGap)
            else:
                self.parent.stoper.Start(self.parent.timeGap)

            self.Destroy()

#-------------------------------------------------------------------------

    def setP(self, message):
        self.radioID = message.data

    #-------------------------------------------------------------------------
    def onPress(self, event):

        if self.pressSound.lower() != 'off':
            self.pressingSound.play()

        self.numberOfEmptyIteration = 0

        # print(self.rowIteration)
        if self.numberOfPresses == 0:

            if self.flag == 'row':

                if (self.rowIteration > 0):
                    self.rowIteration -= 1

                if self.pressSound == "voice":
                    if (self.rowIteration == 0):
                        self.oneSound.play()
                    if (self.rowIteration == 1):
                        self.twoSound.play()
                    if (self.rowIteration == 4):
                        self.fiveSound.play()

                if self.rowIteration == 0 or self.rowIteration == 1:
                    buttonsToHighlight = range(
                        self.rowIteration * self.numberOfColumns[0],
                        self.rowIteration * self.numberOfColumns[0] +
                        self.numberOfColumns[0])
                    for button in buttonsToHighlight:
                        item = self.subSizer.GetItem(button)
                        b = item.GetWindow()
                        b.SetBackgroundColour(self.selectionColour)
                        b.SetFocus()
                    self.flag = 'columns'
                    self.colIteration = 0

                    #self.stoper.Start( self.timeGap )

                elif self.rowIteration == 2:
                    if self.pressSound == "voice":
                        self.pelnyEkranSound.play()

                    buttonsToHighlight = self.rowIteration * self.numberOfColumns[
                        0],
                    for button in buttonsToHighlight:
                        item = self.subSizer.GetItem(button)
                        b = item.GetWindow()
                        b.SetBackgroundColour(self.selectionColour)
                        b.SetFocus()

                    self.rowIteration = 0
                    os.system(
                        "wid=`wmctrl -l | awk '/Minitube/ {print $1}'` && xdotool windowfocus $wid && xdotool key --window $wid F11"
                    )

                    os.system("sleep 1")
                    os.system(
                        "wid=`wmctrl -l | awk '/Pilot/ {print $1}'` && xdotool windowactivate $wid #&& xdotool keydown alt key Tab; sleep 0.1; xdotool keyup alt"
                    )
                    os.system("sleep 0.5")
                    os.system(
                        "wid=`wmctrl -l | awk '/Pilot/ {print $1}'` && xdotool windowraise $wid"
                    )

                elif self.rowIteration == 3:
                    if self.pressSound == "voice":
                        self.zatrzymajGrajSound.play()

                    buttonsToHighlight = self.rowIteration * self.numberOfColumns[
                        0] - 1,
                    for button in buttonsToHighlight:
                        item = self.subSizer.GetItem(button)
                        b = item.GetWindow()
                        b.SetBackgroundColour(self.selectionColour)
                        b.SetFocus()

                    self.rowIteration = 0
                    os.system(
                        "wid=`wmctrl -l | awk '/Minitube/ {print $1}'` && xdotool windowfocus $wid && xdotool key --window --sync $wid space"
                    )
            # self.mouseCursor.click( self.playButtonPosition[self.radioID][0], self.playButtonPosition[self.radioID][1], 1 )
            # time.sleep(0.2)
            # self.mouseCursor.click( self.playButtonPosition[self.radioID][0], self.playButtonPosition[self.radioID][1], 1 )
            ### if download option were available
            # elif self.rowIteration == 4:
            # 	buttonsToHighlight = range(self.rowIteration*self.numberOfColumns[0] - 2, self.rowIteration*self.numberOfColumns[0] + self.numberOfColumns[0] - 2)
            # 	for button in buttonsToHighlight:
            # 		item = self.subSizer.GetItem( button )
            # 		b = item.GetWindow()
            # 		b.SetBackgroundColour( self.selectionColour )
            # 		b.SetFocus()
            # 	self.flag = 'columns'
            # 	self.colIteration = 0

                elif self.rowIteration == 4:
                    buttonsToHighlight = range(
                        self.rowIteration * self.numberOfColumns[0] - 2,
                        self.rowIteration * self.numberOfColumns[0] +
                        self.numberOfColumns[0] - 2)
                    for button in buttonsToHighlight:
                        item = self.subSizer.GetItem(button)
                        b = item.GetWindow()
                        b.SetBackgroundColour(self.selectionColour)
                        b.SetFocus()
                    self.flag = 'columns'
                    self.colIteration = 0

                ### if download option exists
                    # time.sleep(0.5)
                    # cmd = 'wmctrl -l'
                    # p = sp.Popen(cmd, shell=True, stdin=sp.PIPE, stdout=sp.PIPE, stderr=sp.STDOUT, close_fds=True)
                    # output = p.stdout.read()

                    # os.system('milena_say Nie ukończono pobierania materiału. Po ponownym włączeniu proszę rozpocząć pobieranie od początku')
                    # path = '/home/jgrynczewski/Desktop/changes/youtube playlist'
                    # files = os.listdir(path)
                    # files.sort(key=lambda f: os.path.getmtime(os.path.join(path, f)))
                    # os.system( 'rm ./youtube\ playlist/%s' % files[-1].replace(' ', '\ ') )

            elif self.flag == 'columns':

                self.colIteration -= 1

                if self.rowIteration == 0 or self.rowIteration == 1:
                    self.position = self.rowIteration * self.numberOfColumns[
                        0] + self.colIteration + 1

                if self.rowIteration == 4:
                    self.position = self.rowIteration * self.numberOfColumns[
                        0] + self.colIteration + 1 - 2

                item = self.subSizer.GetItem(self.position - 1)
                selectedButton = item.GetWindow()
                selectedButton.SetBackgroundColour(self.selectionColour)
                selectedButton.SetFocus()

                self.Update()

                # print self.radios[self.position][0]
                if self.radios[self.position][0] == 'volume down':
                    try:
                        if self.pressSound == "voice":
                            self.ciszejSound.play()

                        self.reader.readParameters()
                        parameters = self.reader.getParameters()
                        self.unpackParameters(parameters)

                        if self.volumeLevel == 0:
                            raise alsaaudio.ALSAAudioError
                        else:
                            for idx, item in enumerate(self.volumeLevels):
                                if self.volumeLevel == item:
                                    self.volumeLevel = self.volumeLevels[idx -
                                                                         1]
                                    break

                        os.system(
                            "pactl set-sink-volume alsa_output.pci-0000_00_1b.0.analog-stereo %d%%"
                            % self.volumeLevel)
                        self.reader.saveVolume(self.volumeLevel)
                        time.sleep(1.5)

                    except alsaaudio.ALSAAudioError:
                        selectedButton.SetBackgroundColour('red')
                        selectedButton.SetFocus()

                        self.Update()
                        time.sleep(1.5)

                elif self.radios[self.position][0] == 'volume up':
                    try:
                        if self.pressSound == "voice":
                            self.glosniejSound.play()

                        self.reader.readParameters()
                        parameters = self.reader.getParameters()
                        self.unpackParameters(parameters)

                        if self.volumeLevel == 160:
                            raise alsaaudio.ALSAAudioError
                        else:
                            for idx, item in enumerate(self.volumeLevels):
                                if self.volumeLevel == item:
                                    self.volumeLevel = self.volumeLevels[idx +
                                                                         1]
                                    break

                        os.system(
                            "pactl set-sink-volume alsa_output.pci-0000_00_1b.0.analog-stereo %d%%"
                            % self.volumeLevel)
                        self.reader.saveVolume(self.volumeLevel)

                        time.sleep(1.5)

                    except alsaaudio.ALSAAudioError:
                        selectedButton.SetBackgroundColour('red')
                        selectedButton.SetFocus()

                        self.Update()
                        time.sleep(1.5)

########################
# elif self.radios[self.position][0] == 'undo':
# 	# os.system('wmctrl -c "ATPlatform radio"')
# 	os.system('wmctrl -c Mozilla')

# 	cmd = 'wmctrl -l'
# 	p = Popen(cmd, shell=True, stdin=PIPE, stdout=PIPE, stderr=STDOUT, close_fds=True)
# 	output = p.stdout.read()
# 	print output
# 	if 'minitube' in output:

# 	os.system('wid=`xdotool search --onlyvisible --name minitube|head -1` && xdotool windowfocus $wid && xdotool windowactivate $wid && sleep 0.2 && xdotool key Escape && xdotool key Escape')

# self.stoper.Stop()
# self.menu = radios(self, id=-1 )
# self.Hide()
# self.menu.Show()

# elif self.radios[self.position][0] == 'expand':
# 	os.system('wid=`xdotool search --onlyvisible --name Minitube` && xdotool windowfocus $wid && xdotool key --window $wid F11 && wid=`xdotool search --onlyvisible --name Pilot` && xdotool windowactivate $wid') #&& xdotool keydown alt key Tab; sleep 1; xdotool keyup alt')  #&& wid2=`xdotool search --onlyvisible --name Pilot` && xdotool windowraise $wid2')

                if self.radios[self.position][0] == 'previous':
                    if self.pressSound == "voice":
                        self.poprzedniSound.play()
                    os.system(
                        "wid=`wmctrl -l | awk '/Minitube/ {print $1}'` && xdotool windowfocus $wid && xdotool key --window --sync $wid ctrl+Left"
                    )

                elif self.radios[self.position][0] == 'next':
                    if self.pressSound == "voice":
                        self.nastepnySound.play()
                    os.system(
                        "wid=`wmctrl -l | awk '/Minitube/ {print $1}'` && xdotool windowfocus $wid && xdotool key --window --sync $wid ctrl+Right"
                    )

                elif self.radios[self.position][0] == 'tab switch':
                    if self.pressSound == "voice":
                        self.powrotSound.play()

                    buttonsToHighlight = self.rowIteration * self.numberOfColumns[
                        0] - 2,
                    for button in buttonsToHighlight:
                        item = self.subSizer.GetItem(button)
                        b = item.GetWindow()
                        b.SetBackgroundColour(self.selectionColour)
                        b.SetFocus()

                    self.onExit()

                elif self.radios[self.position][0] == 'download':
                    if self.pressSound == "voice":
                        self.wyjscieSound.play()

                    buttonsToHighlight = self.rowIteration * self.numberOfColumns[
                        0] - 2,
                    for button in buttonsToHighlight:
                        item = self.subSizer.GetItem(button)
                        b = item.GetWindow()
                        b.SetBackgroundColour(self.selectionColour)
                        b.SetFocus()

                    os.system('wmctrl -c Minitube')
                    self.onExit()

                ### if download were available
            # elif self.radios[self.position][0] == 'download':
            # 	os.system("wid=`wmctrl -l | awk '/Minitube/ {print $1}'` && xdotool windowfocus $wid && xdotool key --window $wid ctrl+s")

            # elif self.radios[self.position][0] == 'tab switch':
            # 	os.system("wid=`wmctrl -l | awk '/Minitube/ {print $1}'` && xdotool windowfocus $wid && xdotool key --window $wid ctrl+j")

            # elif self.radios[self.position][0] == 'undo':
            # self.stoper.Stop()
            # self.menu = radios(self, id=-1 )

            #self.message = self.radioID
            #Publisher().sendMessage( ( 'radioID' ), self.message ) #call the Publisher object’s sendMessage method and pass it the topic string and the message in order to send the message

            #self.message = 'ON'
            #Publisher().sendMessage( ( 'radioFlag' ), self.message ) #call the Publisher object’s sendMessage method and pass it the topic string and the message in order to send the message

            # self.Hide()
            # self.menu.Show()

                selectedButton.SetBackgroundColour(self.backgroundColour)

                self.flag = 'row'
                self.panelIteration = 0
                self.rowIteration = 0
                self.colIteration = 0
                self.count = 0
                #self.stoper.Start( self.timeGap )

            self.numberOfPresses += 1

    #-------------------------------------------------------------------------
    def timerUpdate(self, event):

        # print("####################")
        # print "flag = ", self.flag
        # print "rowIter = ", self.rowIteration
        # print "colIter = ", self.colIteration
        # print("####################")

        self.mouseCursor.move(self.dw - 225, self.dh - 265)

        self.numberOfPresses = 0

        if self.numberOfEmptyIteration < 3:

            if self.switchSound.lower() == 'on':
                self.switchingSound.play()

            if self.flag == 'row':  #flag == row ie. switching between rows

                self.numberOfEmptyIteration += 1. / self.numberOfRows[0]

                if self.rowIteration == self.numberOfRows[0]:
                    self.rowIteration = 0

                items = self.subSizer.GetChildren()
                for item in items:
                    b = item.GetWindow()
                    b.SetBackgroundColour(self.backgroundColour)
                    b.SetFocus()

                if self.switchSound == "voice":
                    if (self.rowIteration == 0):
                        self.oneSound.play()
                    if (self.rowIteration == 1):
                        self.twoSound.play()
                    if (self.rowIteration == 4):
                        self.fiveSound.play()

                if self.rowIteration == 0 or self.rowIteration == 1:
                    zakres = range(
                        self.rowIteration * self.numberOfColumns[0],
                        self.rowIteration * self.numberOfColumns[0] +
                        self.numberOfColumns[0])
                elif self.rowIteration == 4:
                    zakres = range(
                        self.rowIteration * self.numberOfColumns[0] - 2,
                        self.rowIteration * self.numberOfColumns[0] +
                        self.numberOfColumns[0] - 2)

                elif self.rowIteration == 2:
                    if self.switchSound == "voice":
                        self.pelnyEkranSound.play()
                    zakres = self.rowIteration * self.numberOfColumns[0],

                elif self.rowIteration == 3:
                    if self.switchSound == "voice":
                        self.zatrzymajGrajSound.play()
                    zakres = self.rowIteration * self.numberOfColumns[0] - 1,

                # elif self.rowIteration == 4:
                # 	zakres = range(self.rowIteration*self.numberOfColumns[0] - 2, self.rowIteration*self.numberOfColumns[0] + self.numberOfColumns[0] - 2)
                # elif self.rowIteration == 4:
                #         if self.switchSound == "voice":
                #                 self.powrotSound.play()
                # 	zakres = self.rowIteration*self.numberOfColumns[0] - 2,

                for i in zakres:
                    item = self.subSizer.GetItem(i)
                    b = item.GetWindow()
                    b.SetBackgroundColour(self.scanningColour)
                    b.SetFocus()
                self.rowIteration += 1

            elif self.flag == 'columns':  #flag = columns ie. switching between cells in the particular row

                if self.countColumns == self.countMaxColumns:
                    self.flag = 'row'
                    self.rowIteration = 0
                    self.colIteration = 0
                    self.countColumns = 0
                    self.countRows = 0

                    items = self.subSizer.GetChildren()
                    for item in items:
                        b = item.GetWindow()
                        b.SetBackgroundColour(self.backgroundColour)
                        b.SetFocus()

                else:
                    if self.colIteration == self.numberOfColumns[0]:
                        self.colIteration = 0

                    if self.colIteration == self.numberOfColumns[0] - 1:
                        self.countColumns += 1

                    items = self.subSizer.GetChildren()
                    for item in items:
                        b = item.GetWindow()
                        b.SetBackgroundColour(self.backgroundColour)
                        b.SetFocus()

                    if self.rowIteration == 0:
                        item = self.subSizer.GetItem(self.rowIteration *
                                                     self.numberOfColumns[0] +
                                                     self.colIteration)

                    elif self.rowIteration == 1:
                        item = self.subSizer.GetItem(self.rowIteration *
                                                     self.numberOfColumns[0] +
                                                     self.colIteration)

                    elif self.rowIteration == 4:
                        item = self.subSizer.GetItem(self.rowIteration *
                                                     self.numberOfColumns[0] +
                                                     self.colIteration - 2)

            # if download option was available
                    # elif self.rowIteration == 4:
                    # elif self.rowIteration == 4:
                    # 	zakres = range(self.rowIteration*self.numberOfColumns[0] - 2, self.rowIteration*self.numberOfColumns[0] + self.numberOfColumns[0] - 2)
                    # elif self.rowIteration == 4:
                    #         if self.switchSound == "voice":
                    #                 self.powrotSound.play()
                    # 	zakres = self.rowIteration*self.numberOfColumns[0] - 2,
                    # 	item = self.subSizer.GetItem( self.rowIteration*self.numberOfColumns[ 0 ] + self.colIteration - 2 )
                    b = item.GetWindow()
                    b.SetBackgroundColour(self.scanningColour)
                    b.SetFocus()
                    logo = b.Name

                    if self.switchSound == "voice":
                        if logo == 'volume down':
                            self.ciszejSound.play()
                        if logo == 'volume up':
                            self.glosniejSound.play()
                        if logo == 'previous':
                            self.poprzedniSound.play()
                        if logo == 'next':
                            self.nastepnySound.play()
                        if logo == 'undo':
                            self.powrotSound.play()
                        if logo == 'cancel':
                            self.wyjscieSound.play()

                    self.colIteration += 1

        else:
            if self.switchSound == 'voice':
                self.usypiamSound.play()

            self.stoper.Stop()
            suspend.suspend(self, id=2).Show(True)
            self.Hide()
            self.numberOfEmptyIteration = 0
Example #57
0
#imports
from Tkinter import *
from pykeyboard import PyKeyboard
from pymouse import PyMouse
import tkFileDialog, tkMessageBox
import os
import time
import ctypes
import platform

#initialize Objects
master = Tk()
master.wm_title("pyScraper")
kb = PyKeyboard()
m = PyMouse()

#global Vars
readyForMouseInput = False
if platform.system() == "Darwin":
	specialkeys = {"Special Keys":""}
else:
	specialkeys= {"Special Keys":"","Tab":kb.tab_key,"Shift":kb.shift_key,"Enter":kb.enter_key,\
					"Ctrl":kb.control_key,"Alt":kb.alt_key, "Del":kb.delete_key,\
					"Insert":kb.insert_key,"Esc":kb.escape_key,"F1":kb.function_keys[1],\
					"F2":kb.function_keys[2],"F3":kb.function_keys[3],"F4":kb.function_keys[4],
					"F5":kb.function_keys[5],"F6":kb.function_keys[6],"F7":kb.function_keys[7],\
					"F8":kb.function_keys[8],"F9":kb.function_keys[9],"F10":kb.function_keys[10],\
					"F11":kb.function_keys[11],"F12":kb.function_keys[12]}
specialkeysorder= {"Special Keys":1,"Tab":2,"Shift":3,"Enter":4,\
					"Ctrl":5,"Alt":6, "Del":7,\
					"Insert":8,"Esc":9,"F1":10,\
from time import sleep, time
from Smoothening_Functions.SmootheningFunctions import smoothening as smth
smth = smth()


def click(x, y):
    win32api.SetCursorPos((x, y))
    win32api.mouse_event(win32con.MOUSEEVENTF_LEFTDOWN, x, y, 0, 0)
    win32api.mouse_event(win32con.MOUSEEVENTF_LEFTUP, x, y, 0, 0)


# Instantiate a mouse and a keyboard.
# A PyMouse() and a PyKeyboard() have certain methods that allow
# easy access to typical features of such peripherals like moving the
# pointer to a certain position or pressing keyboard buttons.
mouse = PyMouse()
keyboard = PyKeyboard()

# Just reminding the user of sth. very important.

SmallestDisplist = smth.numberandcyclesfromdisplist(
    self, disp=0.0, metadatadict={}, findsmallestdispincycle=True)

print(SmallestDisplist)
#highest_numbers=np.arange(27,329,12)
#start_heres=np.arange(16,317,12)
waittime = 0.8
analysis_time = 2
save_time = 2
RRef = True
base_filenames = ["F_08_fibre 3_",
Example #59
0
import numpy as np
from PIL import ImageGrab
# import pyscreenshot as ImageGrab
import cv2
import time
from pymouse import PyMouse
from pykeyboard import PyKeyboard

TOP_LEFT = (630, 330)
NEW_GAME_PIXEL = (TOP_LEFT[0] + 325, TOP_LEFT[1] + 345)

for i in list(range(4))[::-1]:
    print(i + 1)
    time.sleep(1)

m = PyMouse()
k = PyKeyboard()

m.click(NEW_GAME_PIXEL[0], NEW_GAME_PIXEL[1], 1)

k.press_key(k.right_key)
for i in list(range(4))[::-1]:
    print(i + 1)
    time.sleep(1)
k.release_key(k.right_key)

k.press_key(k.left_key)
for i in list(range(4))[::-1]:
    print(i + 1)
    time.sleep(1)
k.release_key(k.left_key)
	def showVideo(self,click_allow_arg):
		lower_IR = np.array([0,0,50]) # lower bound of CV filter
		upper_IR = np.array([255,255,255]) # upper bound of CV filter
		rawCapture = PiRGBArray(self.cam_handle, size=self.cam_res) # capture to array
		m = PyMouse() # make mouse object
		prev_maxLoc = (0,0) # init previous maxLoc
		try:
			for frame in self.cam_handle.capture_continuous(rawCapture, format = 'bgr', use_video_port=True):
				image = frame.array # get the array values for that frame
				mask = cv2.inRange(image, lower_IR, upper_IR) # mask according to lower/upper filter values
				(minVal, maxVal, minLoc, maxLoc) = cv2.minMaxLoc(mask) # find min/max values of image
				true_pnt = self.get_true_point(maxLoc)
				print true_pnt #DEBUG INFO PRINTOUT
				adjusted_maxx = int(((true_pnt[0]) * self.output_res[0])/(self.screen_res[0])) # take the distance from the edge and perform dimensional analysis
				adjusted_maxy = int(((true_pnt[1]) * self.output_res[1])/(self.screen_res[1])) # take the distance from the edge and perform dimensional analysis
				if click_allow_arg: # if user wants to have clicks when IR found
					if maxLoc != (0,0): # if not on the default location			
						m.press(adjusted_maxx,adjusted_maxy, 1) # press the "mouse" button at location found
					elif prev_maxLoc != (0,0) and maxLoc == (0,0): # if the current value is the default and the last value wasn't the default, release
						m.release(prev_maxLoc[0],prev_maxLoc[1], 1) # release the "mouse" button
				else: # only move the mouse, no clicking
					if maxLoc != (0,0): # if not on the default location
						m.move(adjusted_maxx,adjusted_maxy) # move the mouse
				prev_maxLoc = (adjusted_maxx,adjusted_maxy) # set previous to be current max loc
				cv2.circle(image, maxLoc, 21, (255,0,0), 2) # place circle on brightest spot
				cv2.imshow("TestWindow", cv2.resize(image,(160,120))) # show the image in a tiny window
				cv2.waitKey(1) & 0xFF # needed for preview
				rawCapture.seek(0) # return to the 0th byte
				rawCapture.truncate() # clear array for next frame
				print "Mouse at: ", m.position() #DEBUG INFO PRINTOUT
		except KeyboardInterrupt: # used to quit the function
			rawCapture.seek(0) # return to the 0th byte
			rawCapture.truncate() # clear array for next frame