Example #1
0
    def __init__(self):
        height, width = self.get_terminal_size()
        self.screen = aalib.AsciiScreen(height=height, width=width)

        # init tty attributes
        self._tty_settings = termios.tcgetattr(sys.stdin)
        tty.setcbreak(sys.stdin.fileno())
Example #2
0
    def trigger_loop():
        is_posix = sys.platform != 'win32'
        old_count = workflow.pages_shot
        if is_posix:
            import select
            old_settings = termios.tcgetattr(sys.stdin)
            data_available = lambda: (select.select([sys.stdin], [], [], 0) ==
                                     ([sys.stdin], [], []))
            read_char = lambda: sys.stdin.read(1)
        else:
            data_available = msvcrt.kbhit
            read_char = msvcrt.getch

        try:
            if is_posix:
                tty.setcbreak(sys.stdin.fileno())
            while True:
                time.sleep(0.01)
                if workflow.pages_shot != old_count:
                    old_count = workflow.pages_shot
                    refresh_stats()
                if not data_available():
                    continue
                char = read_char()
                if char in tuple(capture_keys) + ('r', ):
                    workflow.capture(retake=(char == 'r'))
                    refresh_stats()
                elif char == 'f':
                    break
        finally:
            if is_posix:
                termios.tcsetattr(sys.stdin, termios.TCSADRAIN, old_settings)
Example #3
0
def console():
    old_attrs = termios.tcgetattr(sys.stdin)
    tty.setcbreak(sys.stdin)
    try:
        yield
    finally:
        termios.tcsetattr(sys.stdin, termios.TCSADRAIN, old_attrs)
Example #4
0
def interactive_shell(chan):
    """stolen from paramiko examples"""
    oldtty = termios.tcgetattr(sys.stdin)
    try:
        tty.setraw(sys.stdin.fileno())
        tty.setcbreak(sys.stdin.fileno())
        chan.settimeout(0.0)

        while True:
            r, w, e = select.select([chan, sys.stdin], [], [])
            if chan in r:
                try:
                    x = chan.recv(1024)
                    if len(x) == 0:
                        break
                    sys.stdout.write(x)
                    sys.stdout.flush()
                except socket.timeout:
                    pass
            if sys.stdin in r:
                x = sys.stdin.read(1)
                if len(x) == 0:
                    break
                chan.send(x)

    finally:
        termios.tcsetattr(sys.stdin, termios.TCSADRAIN, oldtty)
Example #5
0
    def _posix_shell(self, chan):
        import select

        oldtty = termios.tcgetattr(sys.stdin)
        try:
            tty.setraw(sys.stdin.fileno())
            tty.setcbreak(sys.stdin.fileno())
            chan.settimeout(0.0)

            # needs to be sent to give vim correct size FIX
            chan.send('eval $(resize)\n')

            while True:
                r, w, e = select.select([chan, sys.stdin], [], [])
                if chan in r:
                    try:
                        x = chan.recv(1024)
                        if len(x) == 0:
                            print '\r\n*** EOF\r\n',
                            break
                        sys.stdout.write(x)
                        sys.stdout.flush()
                    except socket.timeout:
                        pass
                if sys.stdin in r:
                    # fixes up arrow problem
                    x = os.read(sys.stdin.fileno(), 1)
                    if len(x) == 0:
                        break
                    chan.send(x)
        finally:
            termios.tcsetattr(sys.stdin, termios.TCSADRAIN, oldtty)
    def handle(self):
        print "\n[!!] K4P0W!@# -> shell from %s" % self.client_address[0]
        print "[**] This shell is powered by insane amounts of illegal substances"
  
        s = self.request
  
        import termios, tty, select, os
        old_settings = termios.tcgetattr(0)
 
        try:
            tty.setcbreak(0)
            c = True
 
            os.write(s.fileno(), "id\nuname -a\n")
 
            while c:
                for i in select.select([0, s.fileno()], [], [], 0)[0]:
                    c = os.read(i, 1024)
                    if c:
                        if i == 0:
                            os.write(1, c)
  
                        os.write(s.fileno() if i == 0 else 1, c)
        except KeyboardInterrupt: pass
        finally: termios.tcsetattr(0, termios.TCSADRAIN, old_settings)
  
        return
Example #7
0
def kp_start_playing():
    """
    Non-stop play the note using keyboard.

    Use ESC to stop.
    """
    def isData():
        return select.select([sys.stdin], [], [], 0) == ([sys.stdin], [], [])

    old_settings = termios.tcgetattr(sys.stdin)

    try:
        tty.setcbreak(sys.stdin.fileno())
        while True:
            if not isData():
                c = sys.stdin.read(1)
                if c >= '0' and c <= '9' or c == '-' or c == '=':
                    # Valid input, use multiprocessing to prevent problem?
                    # 0 means release
                    p = multiprocessing.Process(target=kp_play_note_once, args=(c,))
                    p.start()
                    # Never join!
                    continue
                elif c == '\x1b': # ESC
                    break
                print('Not valid input.') # Invalid input
    finally:
        termios.tcsetattr(sys.stdin, termios.TCSADRAIN, old_settings)
Example #8
0
    def __init__(self, key='q', timeout=0):
        """Initialize. Specify key and timeout. Put terminal into cbreak mode."""
        #
        # To do:
        # --> enable key combinations (e.g., CTRL+q)
        # --> enable special keys (e.g., ESC)"""
        #

        # get key
        if len(key) != 1:
            raise ValueError('invalid key')
        self.key = key
        ### how to use the ESC key?

        # enable this class
        self.disabled = False

        # initialize the "aborted" flag
        self.aborted = False

        # initialize other attributes
        try:
            self.oldattr = termios.tcgetattr(sys.stdin)
        except:
            self.disabled = True  # disable, probably does not work with nohup
            return

        self.buff = ''  # collect all other pressed keys, in case needed
        self.timeout = timeout
        self.count = 0  # count the total number of checks made

        # enter cbreak mode
        tty.setcbreak(sys.stdin.fileno())
Example #9
0
    def start(self, alternate_buffer=True):
        """
        Initialize the screen and input mode.

        alternate_buffer -- use alternate screen buffer
        """
        assert not self._started
        if alternate_buffer:
            self._term_output_file.write(escape.SWITCH_TO_ALTERNATE_BUFFER)
            self._rows_used = None
        else:
            self._rows_used = 0

        fd = self._term_input_file.fileno()
        if os.isatty(fd):
            self._old_termios_settings = termios.tcgetattr(fd)
            tty.setcbreak(fd)

        self.signal_init()
        self._alternate_buffer = alternate_buffer
        self._input_iter = self._run_input_iter()
        self._next_timeout = self.max_wait

        if not self._signal_keys_set:
            self._old_signal_keys = self.tty_signal_keys(fileno=fd)

        super(Screen, self).start()

        signals.emit_signal(self, INPUT_DESCRIPTORS_CHANGED)
        # restore mouse tracking to previous state
        self._mouse_tracking(self._mouse_tracking_enabled)
Example #10
0
def posix_shell(chan):
    import select
    
    oldtty = termios.tcgetattr(sys.stdin)
    try:
        tty.setraw(sys.stdin.fileno())
        tty.setcbreak(sys.stdin.fileno())
        chan.settimeout(0.0)

        while True:
            r, w, e = select.select([chan, sys.stdin], [], [])
            if chan in r:
                try:
                    x = u(chan.recv(1024))
                    if len(x) == 0:
                        sys.stdout.write('\r\n*** EOF\r\n')
                        break
                    sys.stdout.write(x)
                    sys.stdout.flush()
                except socket.timeout:
                    pass
            if sys.stdin in r:
                x = sys.stdin.read(1)
                if len(x) == 0:
                    break
                chan.send(x)

    finally:
        termios.tcsetattr(sys.stdin, termios.TCSADRAIN, oldtty)
Example #11
0
    def _wait_for_interval(self):
        """Wait for the time interval to expire
        
        This method issues a timing loop to wait for the specified interval to
        expire or quit if the user presses 'q' or 'Q'. The method passes all
        other keyboard requests to the _do_command() method for processing.

        If the interval expires, the method returns None.
        If the user presses a key, the method returns the numeric key number.
        
        Returns - None or int (see above)        
        """
        # If on *nix systems, set the terminal IO sys to not echo
        if os.name == "posix":
            import tty, termios
            old_settings = termios.tcgetattr(sys.stdin)
            tty.setcbreak(sys.stdin.fileno())
            
        key = None
        done = False
        # loop for interval in seconds while detecting keypress 
        while not done:
            done = self.alarm <= time.time()
            if kbhit() and not done:
                key = getch()
                done = True

        # Reset terminal IO sys to older state
        if os.name == "posix":
            termios.tcsetattr(sys.stdin, termios.TCSADRAIN, old_settings)

        return key
Example #12
0
 def __enter__(self):
     self._attr = termios.tcgetattr(sys.stdin)
     tty.setcbreak(sys.stdin.fileno())
     new = termios.tcgetattr(sys.stdin)
     new[0] &= ~termios.ICRNL
     termios.tcsetattr(sys.stdin.fileno(), termios.TCSADRAIN, new)
     return self
Example #13
0
def getOneKey():
    try:
        tty.setcbreak(sys.stdin.fileno())
        ch = sys.stdin.read(1)
        return ord(ch)
    finally:
        termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
 def gameLoop(self):
     """This is  the main game loop."""
     self.reload()
     self.steps = 0
     self.firaNo = 0
     pygame.mixer.init()
     pygame.mixer.music.load("music/route2.mp3")
     pygame.mixer.music.play()
     while True:
         self.__play.getLevelProperties()
         if self.__play.retLives() <= 0:
             break
         tty.setcbreak(sys.stdin)
         key = ord(sys.stdin.read(1))
         if key == 113 or key == 81:
             break
         if key == 32 and not self.__play.inAir():
             self.gameJumpLoop()
         else:
             self.updateEverything(key)
         self.__win = self.__play.victory()
         if self.__win:
             os.system("clear")
             self.reload(self.__play.retScore(), 2)
         if pygame.mixer.music.get_busy() != True:
             pygame.mixer.music.play()
     print "GAME OVER"
Example #15
0
 def __enter__ (self):
     try:
         self.__settings = termios.tcgetattr (sys.stdin)
         tty.setcbreak (sys.stdin.fileno())
     except termios.error:
         self.__settings = None
     return Console (self)
Example #16
0
    def print_ansi(self):
        """Controls the printing of the ANSI art."""
        self._output.write(self.prepare_screen())

        tty.setcbreak(sys.stdin.fileno())
        while True:
            character = self._source_ansi.read(1)
            if not character:
                break
            # DOS EOF, after it comes SAUCE metadata.
            if character == '\x1a':
                break
            self._output.write(self.process(character, self._source_ansi))

            position = self.position_reporter.get_position_report()
            # this is bugged after processing newlines.
            if  position['col'] != self.screen.cursor['col']:
                message = ("wrong pos ({}, {}), processed to {}, actual row: {} "
                "col: {}")
                row = self.screen.cursor['row']
                col = self.screen.cursor['col']
                offset = self._source_ansi.tell()
                rrow = position['row']
                rcol = position['col']
                self.logger.warn(message.format(row, col, offset, rrow, rcol))
        self._output.write(self.close_screen())
Example #17
0
    def interactive(self, command, *args, **options):
        import termios
        import tty
        with self._get_chan(options.pop('get_pty', False)) as chan:
            with self._forward_agent(chan):
                with timeout(self._timeout):
                    command = self._format_command(command, args, options)

                    chan.get_pty()
                    oldtty = termios.tcgetattr(sys.stdin)
                    try:
                        tty.setraw(sys.stdin.fileno())
                        tty.setcbreak(sys.stdin.fileno())
                        chan.settimeout(0.0)
                        chan.exec_command(command)

                        while True:
                            rlist = select.select([chan, sys.stdin], [], [])[0]
                            if chan in rlist:
                                try:
                                    data = self._manage_encoding(chan.recv(1024))
                                    if len(data) == 0:
                                        break
                                    sys.stdout.write(data)
                                    sys.stdout.flush()
                                except socket.timeout:
                                    pass
                            if sys.stdin in rlist:
                                data = sys.stdin.read(1)
                                if len(data) == 0:
                                    break
                                chan.send(data)
                    finally:
                        termios.tcsetattr(sys.stdin, termios.TCSADRAIN, oldtty)
Example #18
0
 def interactive_shell(self, chan):
     sys.stdout.flush()
     try:
         signal.signal(signal.SIGHUP, self._session.kill_session)
         oldtty = termios.tcgetattr(sys.stdin)
         tty.setraw(sys.stdin.fileno())
         tty.setcbreak(sys.stdin.fileno())
         chan.settimeout(0.0)
         while True:
             r, w, e = select.select([chan, sys.stdin], [], [])
             if chan in r:
                 try:
                     x = chan.recv(1024)
                     if len(x) == 0:
                         break
                     sys.stdout.write(x)
                     sys.stdout.flush()
                 except socket.timeout:
                     break
             if sys.stdin in r:
                 x = os.read(sys.stdin.fileno(), 1)
                 if len(x) == 0:
                     break
                 chan.send(x)
         termios.tcsetattr(sys.stdin, termios.TCSADRAIN, oldtty)
     except Exception as e:
         logger.error(e.message)
         raise e
Example #19
0
def getch(prompt=''):

	"""Reads a character from standard input.

	If the user enters a newline, an empty string is returned. For the most
	part, this behaves just like input().  An optional prompt can be
	provided.

	"""

	print(prompt, end='')
	sys.stdout.flush()

	# Windows
	try:
		char = msvcrt.getwch()
	except NameError:
		pass
	else:
		if char == '\r' or char == '\n':
			char = ''

		print(char, end='')
		sys.stdout.flush()

		return char

	# Unix
	file_number = sys.stdin.fileno()
	try:
		old_settings = termios.tcgetattr(file_number)
	except NameError:
		pass
	except termios.error:
		pass
	else:
		tty.setcbreak(file_number)

	try:
		char = chr(27)
		if sys.stdin.isatty():
			# avoid escape sequences and other undesired characters
			while ord(char[0]) in (8, 27, 127):
				char = sys.stdin.read(len(sys.stdin.buffer.peek(1)))
		else:
			char = sys.stdin.read(1)

		if char == '\r' or char == '\n':
			char = ''

		if 'old_settings' in locals():
			print(char, end='')
			sys.stdout.flush()
	finally:
		try:
			termios.tcsetattr(file_number, termios.TCSADRAIN, old_settings)
		except NameError:
			pass

	return char
Example #20
0
def posix_shell(chan):
    """
    POSIX shell implementation for proxied SSH.

    Lifted from Paramiko examples.
    """
    import select
    
    oldtty = termios.tcgetattr(sys.stdin)
    try:
        tty.setraw(sys.stdin.fileno())
        tty.setcbreak(sys.stdin.fileno())
        chan.settimeout(0.0)

        while True:
            r, w, e = select.select([chan, sys.stdin], [], [])
            if chan in r:
                try:
                    x = chan.recv(1024)
                    if len(x) == 0:
                        print '\r\n*** EOF\r\n',
                        break
                    sys.stdout.write(x)
                    sys.stdout.flush()
                except socket.timeout:
                    pass
            if sys.stdin in r:
                x = sys.stdin.read(1)
                if len(x) == 0:
                    break
                chan.send(x)

    finally:
        termios.tcsetattr(sys.stdin, termios.TCSADRAIN, oldtty)
Example #21
0
def posix_shell(chan,logfile):
    import select
    
    oldtty = termios.tcgetattr(sys.stdin)
    f=open(logfile,'w')
    try:
        mode = tty.tcgetattr(sys.stdin.fileno())
        tty.setraw(sys.stdin.fileno())
        tty.setcbreak(sys.stdin.fileno())
        chan.settimeout(0.0)

        while True:
            r, w, e = select.select([chan, sys.stdin], [], [])
            if chan in r:
                try:
                    x = chan.recv(1024)
                    if len(x) == 0:
                        sys.stdout.write('\r\n*** EOF\r\n')
                        break
                    sys.stdout.write(x)
                    sys.stdout.flush()
                    f.write(x)
                    f.flush()
                except socket.timeout:
                    pass
            if sys.stdin in r:
                #x = sys.stdin.read(1)
                x=os.read(sys.stdin.fileno(),1000)
                if len(x) == 0:
                    break
                chan.send(x)

    finally:
        termios.tcsetattr(sys.stdin, termios.TCSADRAIN, oldtty)
        f.close()
Example #22
0
def posix_shell(chan,username,hostname):
    import select
    
    oldtty = termios.tcgetattr(sys.stdin)
    try:
        tty.setraw(sys.stdin.fileno())
        tty.setcbreak(sys.stdin.fileno())
        chan.setblocking(1)
        day_time=time.strftime('%Y_%m_%d')
        f=open('/mama100/mama100/static/test.txt','a')
        print "begin"
        while True:
            r, w, e = select.select([chan, sys.stdin], [], [])
            if chan in r:
                try:
                    x = chan.recv(1024)
                    #if not chan.recv_ready():
                    #    print '\r\n*** EOF exit\r\n',
                    #    break
                    sys.stdout.write(x) 
                    f.write(str(x))
                    f.flush()
                    sys.stdout.flush()
                except socket.timeout:
                    pass
            if sys.stdin in r:
                x = sys.stdin.read(1)
                if len(x) == 0:
                    break
                chan.send(x)
        f.close()
    finally:
        termios.tcsetattr(sys.stdin, termios.TCSADRAIN, oldtty)
Example #23
0
 def __enter__(self):
     self.original_stty = termios.tcgetattr(self.in_stream)
     tty.setcbreak(self.in_stream, termios.TCSANOW)
     if self.sigint_event:
         self.orig_sigint_handler = signal.getsignal(signal.SIGINT)
         signal.signal(signal.SIGINT, self.sigint_handler)
     return self
Example #24
0
 def run ( self ):
     
     self._done.clear()
     
     if ( platform.system() == 'Windows'):
         while not self._done.isSet():
             # We use kbhit() to see if anything has been entered yet.
             # This is important, because if we don't then we will block
             #   on getch() and be unable to tell when _done.isSet().
             if msvcrt.kbhit(): 
                 self.pushChar(msvcrt.getch())
     else:
         ''' we're not on Windows, so we try the Unix-like approach '''
         
         fd = sys.stdin.fileno( )
         old_settings = termios.tcgetattr(sys.stdin)
         try:
             tty.setcbreak(fd)
             
             while not self._done.isSet():
                 # We use _isData() to see if anything has been entered yet.
                 # This is important, because if we don't then we will block
                 #   on stdin.read() and be unable to tell when _done.isSet().
                 if _isData():
                     self.pushChar(sys.stdin.read(1))
                 
         finally:
             termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
Example #25
0
def posix_shell(chan,ip,username,group): #unix交互
    import select

    oldtty = termios.tcgetattr(sys.stdin)
    try:
        tty.setraw(sys.stdin.fileno())
        tty.setcbreak(sys.stdin.fileno())
        chan.settimeout(0.0)

        while True:
            r, w, e = select.select([chan, sys.stdin], [], [])
            if chan in r:
                try:
                    x = chan.recv(1024)
                    if len(x) == 0:
                        print '\r\n*** EOF\r\n',
                        break
                    sys.stdout.write(x)
                    sys.stdout.flush()
                except socket.timeout:
                    pass
                logger(ip,username,group,x)

            if sys.stdin in r:
                x = sys.stdin.read(1) #写入日志
                if len(x) == 0:
                    break
                chan.send(x)

    finally:
        termios.tcsetattr(sys.stdin, termios.TCSADRAIN, oldtty)
Example #26
0
def ssh_interactive(chan):
    """Stolen from paramiko.demos.interactive."""
    import select
    import socket
    import termios
    import tty

    oldtty = termios.tcgetattr(sys.stdin)
    try:
        tty.setraw(sys.stdin.fileno())
        tty.setcbreak(sys.stdin.fileno())
        chan.settimeout(0.0)

        while True:
            r, w, e = select.select([chan, sys.stdin], [], [])
            if chan in r:
                try:
                    x = chan.recv(1024).decode('utf-8')
                    if len(x) == 0:
                        sys.stdout.write('\r\n*** EOF\r\n')
                        break
                    sys.stdout.write(x)
                    sys.stdout.flush()
                except socket.timeout:
                    pass
            if sys.stdin in r:
                x = sys.stdin.read(1)
                if len(x) == 0:
                    break
                chan.send(x)

    finally:
        termios.tcsetattr(sys.stdin, termios.TCSADRAIN, oldtty)
Example #27
0
    def unbuffered_input(self):
        '''Context manager for setting the terminal to use unbuffered input.

        Normally, your terminal will collect together a user's input
        keystrokes and deliver them to you in one neat parcel when they hit
        the return/enter key. In a real-time interactive application we instead
        want to receive each keystroke as it happens.

        This context manager achieves that by setting 'cbreak' mode on the
        the output tty stream. cbreak is a mode inbetween 'cooked mode', where
        all the user's input is preprocessed, and 'raw mode' where none of it
        is. Basically, in cbreak mode input like :kbd:`Control-c` will still
        interrupt (i.e. 'break') the process, hence the name. Wikipedia is your
        friend on this one!

        :meth:`Root.run` uses this context manager for you to make your
        application work in the correct way.
        '''
        if self.is_a_tty:
            orig_tty_attrs = termios.tcgetattr(self.stream)
            tty.setcbreak(self.stream)
            try:
                yield
            finally:
                termios.tcsetattr(
                    self.stream, termios.TCSADRAIN, orig_tty_attrs)
        else:
            yield
Example #28
0
    def run(self, cb):
        # This method starts the non-blocking terminal.
        #
        # A callback must be passed in to handle user key input. It will be called
        # for every key press.
        #
        # This implementation does not handle multi-byte characters, such as
        # arrow keys. A previous version of this code did handle this case, but
        # decided that it got kind of messy.

        signal.signal(signal.SIGINT, signalHandler)

        old_settings = termios.tcgetattr(sys.stdin)

        fd = sys.stdin.fileno()
        fl = fcntl.fcntl(fd, fcntl.F_GETFL)
        fcntl.fcntl(fd, fcntl.F_SETFL, fl | os.O_NONBLOCK)

        try:
            tty.setcbreak(sys.stdin.fileno())
            while True:
                time.sleep(self.delay)
                if self.hasData():
                    cb()
        finally:
            termios.tcsetattr(sys.stdin, termios.TCSADRAIN, old_settings)
Example #29
0
def term(ssh_channel):
    oldtty = termios.tcgetattr(sys.stdin)
    try:
        tty.setraw(sys.stdin.fileno())
        tty.setcbreak(sys.stdin.fileno())
        ssh_channel.settimeout(0.0)

        while True:
            r, w, e = select.select([ssh_channel, sys.stdin], [], [])
            if ssh_channel in r:
                try:
                    x = u(ssh_channel.recv(1024))
                    if len(x) == 0:
                        sys.stdout.write('\r\n - Exit SSH Shell -\r\n')
                        break
                    sys.stdout.write(x)
                    sys.stdout.flush()
                except socket.timeout:
                    pass
            if sys.stdin in r:
                x = sys.stdin.read(1)
                if len(x) == 0:
                    break
                ssh_channel.send(x)

    finally:
        termios.tcsetattr(sys.stdin, termios.TCSADRAIN, oldtty)
Example #30
0
	def handle(self):
		global do_brute

		print "\n[!] connectback shell from %s" % self.client_address[0]
		do_brute = False

		s = self.request

		import termios, tty, select, os
		old_settings = termios.tcgetattr(0)
		try:
			tty.setcbreak(0)
			c = True
			while c:
				for i in select.select([0, s.fileno()], [], [], 0)[0]:
					c = os.read(i, 1024)
					if c:
						if i == 0:
							os.write(1, c)

						os.write(s.fileno() if i == 0 else 1, c)
		except KeyboardInterrupt: pass
		finally: termios.tcsetattr(0, termios.TCSADRAIN, old_settings)

		return
Example #31
0
#!/usr/bin/env python2
import sys, select, tty, termios
import rospy
from std_msgs.msg import String

if __name__ == '__main__':
    key_pub = rospy.Publisher('keys', String, queue_size=1)
    rospy.init_node("keyboard_driver")
    rate = rospy.Rate(100)
    old_attr = termios.tcgetattr(sys.stdin)
    tty.setcbreak(sys.stdin.fileno())
    print("Publishing  keystrokes. Press Ctrl-C to exit ...")
    while not rospy.is_shutdown():
        if select.select([sys.stdin], [], [], 0)[0] == [sys.stdin]:
            key_pub.publish(sys.stdin.read(1))
        rate.sleep()
    termios.tcsetattr(sys.stdin, termios.TCSADRAIN, old_attr)
Example #32
0
import tty
import sys
import os
from board import *
from paddle import *
from ball import *
from brick import *
from powerup import *
from all_func import *
import all_func

colorama.init()

if __name__ == "__main__":
    orig_settings = termios.tcgetattr(sys.stdin)
    tty.setcbreak(sys.stdin)
    input = input()
    input.hide_cursor()
    config.time_start = time.time()

    while (1):
        all_func.xcoords = []
        all_func.ycoords = []
        # print(all_func.xcoords)
        #taking inputs
        if input.input_to():
            val = input.getch()
            # print(rows)

            if (val == 'q' or val == 'Q'):
                break
Example #33
0
    def run(self):
        """
    Starts phony service which manages device pairing and setting
    up of hands-free profile services.  This function never returns.
    """
        stdin_fd = sys.stdin.fileno()
        pid = os.fork()
        if not pid:
            #child
            os.setsid()
            bus = phony.base.ipc.BusProvider()
            # Find the first audio card that provides audio input and output mixers.
            audio_card_index = -1
            with phony.bluetooth.adapters.Bluez5(bus) as adapter, \
                 phony.bluetooth.profiles.handsfree.Ofono(bus) as hfp, \
                 phony.audio.alsa.Alsa(card_index=audio_card_index) as audio, \
                 phony.headset.HandsFreeHeadset(bus, adapter, hfp, audio) as hs:
                # Register to receive some bluetooth events
                hs.on_device_connected(self.device_connected)
                hs.on_incoming_call(self.incoming_call)
                hs.on_call_began(self.call_began)
                hs.on_call_ended(self.call_ended)
                hs.start('MyBluetoothHeadset', pincode='1234')
                hs.enable_pairability(timeout=30)
                self._hs = hs

                signal.signal(signal.SIGTERM, process_end)
                signal.signal(signal.SIGINT, process_end)
                signal.signal(signal.SIGUSR1, process_answer_call)
                signal.signal(signal.SIGUSR2, process_dial_number)
                gobject.timeout_add_seconds(1, tick)
                loop = gobject.MainLoop()
                try:
                    loop.run()
                except KeyboardInterrupt:
                    print("Child caught keyborad interrupt")
                return 0
                # Wait forever> gobject.MainLoop().run()
        #parent
        def on_sigchld(signum, frame):
            assert signum == signal.SIGCHLD
            print("Child terminated - terminating parent")
            sys.exit(0)

        signal.signal(signal.SIGCHLD, on_sigchld)
        stdin_attrs = termios.tcgetattr(stdin_fd)
        tty.setcbreak(stdin_fd)
        while True:
            try:
                char = os.read(stdin_fd, 1)
                if char.lower() == "a":
                    os.kill(pid, signal.SIGUSR1)
                if char.lower() == "d":
                    os.kill(pid, signal.SIGUSR2)
            except KeyboardInterrupt:
                print("Forwarding SIGINT to child process")
                os.kill(pid, signal.SIGINT)
            except SystemExit:
                print("Caught SystemExit: cleaning up")
                termios.tcsetattr(stdin_fd, termios.TCSADRAIN, stdin_attrs)
                print("Parent terminated normally")
                return 0
    def start(self):

        self.prev_tty_attributes = termios.tcgetattr(sys.stdin.fileno())
        tty.setcbreak(sys.stdin.fileno())
Example #35
0
def main(prog_args=sys.argv[1:]):
    # in case we changed the location of the settings directory where the
    # config file lives, we need to parse this argument before we parse
    # the rest of the arguments (which can overwrite the options in the
    # config file)
    settings_parser = argparse.ArgumentParser(add_help=False)
    settings_parser.add_argument(
        '-S',
        '--settings',
        nargs=1,
        help='Path to settings, config and temp files directory '
        '[Default=~/.spotify-ripper]')
    args, remaining_argv = settings_parser.parse_known_args(prog_args)
    init_util_globals(args)

    # load config file, overwriting any defaults
    defaults = {
        "bitrate": "320",
        "quality": "320",
        "comp": "10",
        "vbr": "0",
        "partial_check": "weak",
    }
    defaults = load_config(defaults)

    parser = argparse.ArgumentParser(
        prog='spotify-ripper',
        description='Rips Spotify URIs to MP3s with ID3 tags and album covers',
        parents=[settings_parser],
        formatter_class=argparse.RawTextHelpFormatter,
        epilog='''Example usage:
    rip a single file: spotify-ripper -u user spotify:track:52xaypL0Kjzk0ngwv3oBPR
    rip entire playlist: spotify-ripper -u user spotify:user:username:playlist:4vkGNcsS8lRXj4q945NIA4
    rip a list of URIs: spotify-ripper -u user list_of_uris.txt
    rip tracks from Spotify's charts: spotify-ripper -l spotify:charts:regional:global:weekly:latest
    search for tracks to rip: spotify-ripper -l -Q 160 -o "album:Rumours track:'the chain'"
    ''')

    # create group to prevent user from using both the -l and -u option
    is_user_set = defaults.get('user') is not None
    is_last_set = defaults.get('last') is True
    if is_user_set or is_last_set:
        if is_user_set and is_last_set:
            print("spotify-ripper: error: one of the arguments -u/--user "
                  "-l/--last is required")
            sys.exit(1)
        else:
            group = parser.add_mutually_exclusive_group(required=False)
    else:
        group = parser.add_mutually_exclusive_group(required=True)

    encoding_group = parser.add_mutually_exclusive_group(required=False)

    # set defaults
    parser.set_defaults(**defaults)

    try:
        prog_version = pkg_resources.require(
            "spotify-ripper-morgaroth")[0].version
    except Exception:
        prog_version = 'DEV'
    parser.add_argument(
        '-a',
        '--ascii',
        action='store_true',
        help='Convert the file name and the metadata tags to ASCII '
        'encoding [Default=utf-8]')
    encoding_group.add_argument(
        '--aac',
        action='store_true',
        help='Rip songs to AAC format with FreeAAC instead of MP3')
    encoding_group.add_argument(
        '--alac',
        action='store_true',
        help='Rip songs to Apple Lossless format instead of MP3')
    parser.add_argument(
        '--artist-album-type',
        nargs=1,
        help='Only load albums of specified types when passing a Spotify '
        'artist URI [Default=album,single,ep,compilation,appears_on]')
    parser.add_argument(
        '--artist-album-market',
        nargs=1,
        help='Only load albums with the specified ISO2 country code when '
        'passing a Spotify artist URI. You may get duplicate albums '
        'if not set. [Default=any]')
    parser.add_argument(
        '-A',
        '--ascii-path-only',
        action='store_true',
        help='Convert the file name (but not the metadata tags) to ASCII '
        'encoding [Default=utf-8]')
    parser.add_argument('-b', '--bitrate', help='CBR bitrate [Default=320]')
    parser.add_argument('-c',
                        '--cbr',
                        action='store_true',
                        help='CBR encoding [Default=VBR]')
    parser.add_argument(
        '--comp',
        help='compression complexity for FLAC and Opus [Default=Max]')
    parser.add_argument(
        '--comment',
        nargs=1,
        help='Set comment metadata tag to all songs. Can include '
        'same tags as --format.')
    parser.add_argument(
        '--cover-file',
        nargs=1,
        help='Save album cover image to file name (e.g "cover.jpg") '
        '[Default=embed]')
    parser.add_argument(
        '--cover-file-and-embed',
        nargs=1,
        metavar="COVER_FILE",
        help='Same as --cover-file but embeds the cover image too')
    parser.add_argument(
        '-d',
        '--directory',
        nargs=1,
        help='Base directory where ripped MP3s are saved [Default=cwd]')
    parser.add_argument('--fail-log',
                        nargs=1,
                        help="Logs the list of track URIs that failed to rip")
    encoding_group.add_argument(
        '--flac',
        action='store_true',
        help='Rip songs to lossless FLAC encoding instead of MP3')
    parser.add_argument(
        '-f',
        '--format',
        nargs=1,
        help='Save songs using this path and filename structure (see README)')
    parser.add_argument(
        '--format-case',
        choices=['upper', 'lower', 'capitalize'],
        help='Convert all words of the file name to upper-case, lower-case, '
        'or capitalized')
    parser.add_argument('--flat',
                        action='store_true',
                        help='Save all songs to a single directory '
                        '(overrides --format option)')
    parser.add_argument(
        '--flat-with-index',
        action='store_true',
        help='Similar to --flat [-f] but includes the playlist index at '
        'the start of the song file')
    parser.add_argument(
        '-g',
        '--genres',
        nargs=1,
        choices=['artist', 'album'],
        help='Attempt to retrieve genre information from Spotify\'s '
        'Web API [Default=skip]')
    parser.add_argument(
        '--grouping',
        nargs=1,
        help='Set grouping metadata tag to all songs. Can include '
        'same tags as --format.')
    encoding_group.add_argument(
        '--id3-v23',
        action='store_true',
        help='Store ID3 tags using version v2.3 [Default=v2.4]')
    parser.add_argument('-k',
                        '--key',
                        nargs=1,
                        help='Path to Spotify application key file '
                        '[Default=Settings Directory]')
    group.add_argument('-u', '--user', nargs=1, help='Spotify username')
    parser.add_argument('-p',
                        '--password',
                        nargs=1,
                        help='Spotify password [Default=ask interactively]')
    group.add_argument('-l',
                       '--last',
                       action='store_true',
                       help='Use last login credentials')
    parser.add_argument(
        '-L',
        '--log',
        nargs=1,
        help='Log in a log-friendly format to a file (use - to log to stdout)')
    encoding_group.add_argument(
        '--pcm',
        action='store_true',
        help='Saves a .pcm file with the raw PCM data instead of MP3')
    encoding_group.add_argument(
        '--mp4',
        action='store_true',
        help='Rip songs to MP4/M4A format with Fraunhofer FDK AAC codec '
        'instead of MP3')
    parser.add_argument('--normalize',
                        action='store_true',
                        help='Normalize volume levels of tracks')
    parser.add_argument('-na',
                        '--normalized-ascii',
                        action='store_true',
                        help='Convert the file name to normalized ASCII with '
                        'unicodedata.normalize (NFKD)')
    parser.add_argument('-o',
                        '--overwrite',
                        action='store_true',
                        help='Overwrite existing MP3 files [Default=skip]')
    encoding_group.add_argument(
        '--opus',
        action='store_true',
        help='Rip songs to Opus encoding instead of MP3')
    parser.add_argument(
        '--partial-check',
        choices=['none', 'weak', 'strict'],
        help='Check for and overwrite partially ripped files. "weak" will '
        'err on the side of not re-ripping the file if it is unsure, '
        'whereas "strict" will re-rip the file [Default=weak]')
    parser.add_argument(
        '--play-token-resume',
        metavar="RESUME_AFTER",
        help='If the \'play token\' is lost to a different device using '
        'the same Spotify account, the script will wait a speficied '
        'amount of time before restarting. This argument takes the same '
        'values as --resume-after [Default=abort]')
    parser.add_argument('--playlist-m3u',
                        action='store_true',
                        help='create a m3u file when ripping a playlist')
    parser.add_argument('--playlist-wpl',
                        action='store_true',
                        help='create a wpl file when ripping a playlist')
    parser.add_argument(
        '--playlist-sync',
        action='store_true',
        help='Sync playlist songs (rename and remove old songs)')
    parser.add_argument(
        '-q',
        '--vbr',
        help='VBR quality setting or target bitrate for Opus [Default=0]')
    parser.add_argument('-Q',
                        '--quality',
                        choices=['160', '320', '96'],
                        help='Spotify stream bitrate preference [Default=320]')
    parser.add_argument(
        '--remove-offline-cache',
        action='store_true',
        help='Remove libspotify\'s offline cache directory after the rip'
        'is complete to save disk space')
    parser.add_argument(
        '--resume-after',
        help='Resumes script after a certain amount of time has passed '
        'after stopping (e.g. 1h30m). Alternatively, accepts a specific '
        'time in 24hr format to start after (e.g 03:30, 16:15). '
        'Requires --stop-after option to be set')
    parser.add_argument(
        '-R',
        '--replace',
        nargs="+",
        required=False,
        help='pattern to replace the output filename separated by "/". '
        'The following example replaces all spaces with "_" and all "-" '
        'with ".":'
        '    spotify-ripper --replace " /_" "\-/." uri')
    parser.add_argument('-s',
                        '--strip-colors',
                        action='store_true',
                        help='Strip coloring from output [Default=colors]')
    parser.add_argument(
        '--stereo-mode',
        choices=['j', 's', 'f', 'd', 'm', 'l', 'r'],
        help='Advanced stereo settings for Lame MP3 encoder only')
    parser.add_argument(
        '--stop-after',
        help='Stops script after a certain amount of time has passed '
        '(e.g. 1h30m). Alternatively, accepts a specific time in 24hr '
        'format to stop after (e.g 03:30, 16:15)')
    parser.add_argument('-V',
                        '--version',
                        action='version',
                        version=prog_version)
    encoding_group.add_argument(
        '--wav',
        action='store_true',
        help='Rip songs to uncompressed WAV file instead of MP3')
    encoding_group.add_argument(
        '--vorbis',
        action='store_true',
        help='Rip songs to Ogg Vorbis encoding instead of MP3')
    parser.add_argument('-r',
                        '--remove-from-playlist',
                        action='store_true',
                        help='Delete tracks from playlist after successful '
                        'ripping [Default=no]')
    parser.add_argument(
        'uri',
        nargs="+",
        help='One or more Spotify URI(s) (either URI, a file of URIs or a '
        'search query)')
    args = parser.parse_args(remaining_argv, args)
    init_util_globals(args)

    # kind of a hack to get colorama stripping to work when outputting
    # to a file instead of stdout.  Taken from initialise.py in colorama
    def wrap_stream(stream, convert, strip, autoreset, wrap):
        if wrap:
            wrapper = AnsiToWin32(stream,
                                  convert=convert,
                                  strip=strip,
                                  autoreset=autoreset)
            if wrapper.should_wrap():
                stream = wrapper.stream
        return stream

    args.has_log = args.log is not None
    if args.has_log:
        if args.log[0] == "-":
            init(strip=True)
        else:
            log_file = open(args.log[0], 'a')
            sys.stdout = wrap_stream(log_file, None, True, False, True)
    else:
        init(strip=True if args.strip_colors else None)

    if args.ascii_path_only is True:
        args.ascii = True

    # unless explicitly told not to, we are going to encode
    # for utf-8 by default
    if not args.ascii and sys.version_info < (3, 0):
        sys.stdout = codecs.getwriter('utf-8')(sys.stdout)

    # small sanity check on user option
    if args.user is not None and args.user[0] == "USER":
        print(Fore.RED + "Please pass your username as --user " +
              "<YOUR_USER_NAME> instead of --user USER " +
              "<YOUR_USER_NAME>..." + Fore.RESET)
        sys.exit(1)

    if args.wav:
        args.output_type = "wav"
    elif args.pcm:
        args.output_type = "pcm"
    elif args.flac:
        args.output_type = "flac"
        if args.comp == "10":
            args.comp = "8"
    elif args.vorbis:
        args.output_type = "ogg"
        if args.vbr == "0":
            args.vbr = "9"
    elif args.opus:
        args.output_type = "opus"
        if args.vbr == "0":
            args.vbr = "320"
    elif args.aac:
        args.output_type = "aac"
        if args.vbr == "0":
            args.vbr = "500"
    elif args.mp4:
        args.output_type = "m4a"
        if args.vbr == "0":
            args.vbr = "5"
    elif args.alac:
        args.output_type = "alac.m4a"
    else:
        args.output_type = "mp3"

    # check that encoder tool is available
    encoders = {
        "flac": ("flac", "flac"),
        "aac": ("faac", "faac"),
        "ogg": ("oggenc", "vorbis-tools"),
        "opus": ("opusenc", "opus-tools"),
        "mp3": ("lame", "lame"),
        "m4a": ("fdkaac", "fdk-aac-encoder"),
        "alac.m4a": ("avconv", "libav-tools"),
    }
    if args.output_type in encoders.keys():
        encoder = encoders[args.output_type][0]
        if which(encoder) is None:
            print(Fore.RED + "Missing dependency '" + encoder +
                  "'.  Please install and add to path..." + Fore.RESET)
            # assumes OS X or Ubuntu/Debian
            command_help = ("brew install " if sys.platform == "darwin" else
                            "sudo apt-get install ")
            print("...try " + Fore.YELLOW + command_help +
                  encoders[args.output_type][1] + Fore.RESET)
            sys.exit(1)

    # format string
    if args.flat:
        args.format = ["{artist} - {track_name}.{ext}"]
    elif args.flat_with_index:
        args.format = ["{idx:3} - {artist} - {track_name}.{ext}"]
    elif args.format is None:
        args.format = ["{album_artist}/{album}/{artist} - {track_name}.{ext}"]

    # print some settings
    print(Fore.GREEN + "Spotify Ripper - v" + prog_version + Fore.RESET)

    def encoding_output_str():
        if args.output_type == "wav":
            return "WAV, Stereo 16bit 44100Hz"
        elif args.output_type == "pcm":
            return "Raw Headerless PCM, Stereo 16bit 44100Hz"
        else:
            if args.output_type == "flac":
                return "FLAC, Compression Level: " + args.comp
            elif args.output_type == "alac.m4a":
                return "Apple Lossless (ALAC)"
            elif args.output_type == "ogg":
                codec = "Ogg Vorbis"
            elif args.output_type == "opus":
                codec = "Opus"
            elif args.output_type == "mp3":
                codec = "MP3"
            elif args.output_type == "m4a":
                codec = "MPEG4 AAC"
            elif args.output_type == "aac":
                codec = "AAC"
            else:
                codec = "Unknown"

            if args.cbr:
                return codec + ", CBR " + args.bitrate + " kbps"
            else:
                return codec + ", VBR " + args.vbr

    print(Fore.YELLOW + "  Encoding output:\t" + Fore.RESET +
          encoding_output_str())
    print(Fore.YELLOW + "  Spotify bitrate:\t" + Fore.RESET + args.quality +
          " kbps")

    def unicode_support_str():
        if args.ascii_path_only:
            return "Unicode tags, ASCII file path"
        elif args.ascii:
            return "ASCII only"
        else:
            return "Yes"

    # check that --stop-after and --resume-after options are valid
    if args.stop_after is not None and \
                    parse_time_str(args.stop_after) is None:
        print(Fore.RED + "--stop-after option is not valid" + Fore.RESET)
        sys.exit(1)
    if args.resume_after is not None and \
                    parse_time_str(args.resume_after) is None:
        print(Fore.RED + "--resume-after option is not valid" + Fore.RESET)
        sys.exit(1)
    if args.play_token_resume is not None and \
                    parse_time_str(args.play_token_resume) is None:
        print(Fore.RED + "--play_token_resume option is not valid" +
              Fore.RESET)
        sys.exit(1)

    print(Fore.YELLOW + "  Unicode support:\t" + Fore.RESET +
          unicode_support_str())
    print(Fore.YELLOW + "  Local encoding:\t" + Fore.RESET +
          sys.getdefaultencoding())
    print(Fore.YELLOW + "  Output directory:\t" + Fore.RESET + base_dir())
    print(Fore.YELLOW + "  Settings directory:\t" + Fore.RESET +
          settings_dir())

    print(Fore.YELLOW + "  Format String:\t" + Fore.RESET + args.format[0])
    print(Fore.YELLOW + "  Overwrite files:\t" + Fore.RESET +
          ("Yes" if args.overwrite else "No"))

    # patch a bug when Python 3/MP4
    if sys.version_info >= (3, 0) and args.output_type == "m4a":
        patch_bug_in_mutagen()

    ripper = Ripper(args)
    ripper.start()

    # try to listen for terminal resize events
    # (needs to be called on main thread)
    if not args.has_log:
        ripper.progress.handle_resize()
        signal.signal(signal.SIGWINCH, ripper.progress.handle_resize)

    def hasStdinData():
        return select.select([sys.stdin], [], [], 0) == ([sys.stdin], [], [])

    def abort(set_logged_in=False):
        ripper.abort_rip()
        if set_logged_in:
            ripper.ripper_continue.set()
        ripper.join()
        sys.exit(1)

    def skip():
        if ripper.ripping.is_set():
            ripper.skip.set()

    # check if we were passed a file name or search
    def check_uri_args():
        if len(args.uri) == 1 and path_exists(args.uri[0]):
            args.uri = [
                line.strip() for line in open(args.uri[0])
                if not line.strip().startswith("#") and len(line.strip()) > 0
            ]
        elif len(args.uri) == 1 and not args.uri[0].startswith("spotify:"):
            args.uri = [list(ripper.search_query(args.uri[0]))]

    # login and uri_parse on main thread to catch any KeyboardInterrupt
    try:
        if not ripper.login():
            print(Fore.RED + "Encountered issue while logging into "
                  "Spotify, aborting..." + Fore.RESET)
            abort(set_logged_in=True)
        else:
            check_uri_args()
            ripper.ripper_continue.set()

    except (KeyboardInterrupt, Exception) as e:
        if not isinstance(e, KeyboardInterrupt):
            print(str(e))
        print("\n" + Fore.RED + "Aborting..." + Fore.RESET)
        abort(set_logged_in=True)

    # wait for ripping thread to finish
    stdin_settings = termios.tcgetattr(sys.stdin)
    try:
        tty.setcbreak(sys.stdin.fileno())

        while ripper.isAlive():
            schedule.run_pending()

            # check if the escape button was pressed
            if hasStdinData():
                c = sys.stdin.read(1)
                if c == '\x1b':
                    skip()
            ripper.join(0.1)
    except (KeyboardInterrupt, Exception) as e:
        if not isinstance(e, KeyboardInterrupt):
            print(str(e))
        print("\n" + Fore.RED + "Aborting..." + Fore.RESET)
        abort()
    finally:
        termios.tcsetattr(sys.stdin, termios.TCSADRAIN, stdin_settings)
Example #36
0
def even(i):
	return i & ~1

pykms.draw_text(fb, even((fb_w // 2) - (8 * 3) // 2), 4, "TOP", pykms.white)
pykms.draw_text(fb, even((fb_w // 2) - (8 * 6) // 2), fb_h - 8 - 4, "BOTTOM", pykms.white)
pykms.draw_text(fb, 4, even(((fb_h // 2) - 4)), "L", pykms.white)
pykms.draw_text(fb, fb_w - 8 - 4, even(((fb_h // 2) - 4)), "R", pykms.white)

rots = [ pykms.Rotation.ROTATE_0, pykms.Rotation.ROTATE_90, pykms.Rotation.ROTATE_180, pykms.Rotation.ROTATE_270 ]
cursors = [ "A", "D", "B", "C" ]

print("Use the cursor keys, x and y to change rotation. Press q to quit.")

fd = sys.stdin.fileno()
oldterm = termios.tcgetattr(fd)
tty.setcbreak(fd)

try:
	esc_seq = 0

	current_rot = pykms.Rotation.ROTATE_0

	show_rot_plane(crtc, plane, fb, current_rot, x_scale, y_scale)

	while True:
		c = sys.stdin.read(1)
		#print("Got character {}".format(repr(c)))

		changed = False
		handled = False
Example #37
0
    def posix_shell(self):
        """
        Use paramiko channel connect server interactive.
        使用paramiko模块的channel,连接后端,进入交互式
        """
        log_file_f, log_time_f, log = self.get_log()
        termlog = TermLogRecorder(User.objects.get(id=self.user.id))
        termlog.setid(log.id)
        old_tty = termios.tcgetattr(sys.stdin)
        pre_timestamp = time.time()
        data = ''
        input_mode = False
        try:
            tty.setraw(sys.stdin.fileno())
            tty.setcbreak(sys.stdin.fileno())
            self.channel.settimeout(0.0)

            while True:
                try:
                    r, w, e = select.select([self.channel, sys.stdin], [], [])
                    flag = fcntl.fcntl(sys.stdin, fcntl.F_GETFL, 0)
                    fcntl.fcntl(sys.stdin.fileno(), fcntl.F_SETFL,
                                flag | os.O_NONBLOCK)
                except Exception:
                    pass

                if self.channel in r:
                    try:
                        x = self.channel.recv(10240)
                        if len(x) == 0:
                            break

                        index = 0
                        len_x = len(x)
                        while index < len_x:
                            try:
                                n = os.write(sys.stdout.fileno(), x[index:])
                                sys.stdout.flush()
                                index += n
                            except OSError as msg:
                                if msg.errno == errno.EAGAIN:
                                    continue
                        now_timestamp = time.time()
                        termlog.write(x)
                        termlog.recoder = False
                        log_time_f.write(
                            '%s %s\n' %
                            (round(now_timestamp - pre_timestamp, 4), len(x)))
                        log_time_f.flush()
                        log_file_f.write(x)
                        log_file_f.flush()
                        pre_timestamp = now_timestamp
                        log_file_f.flush()

                        self.vim_data += x
                        if input_mode:
                            data += x

                    except socket.timeout:
                        pass

                if sys.stdin in r:
                    try:
                        x = os.read(sys.stdin.fileno(), 4096)
                    except OSError:
                        pass
                    termlog.recoder = True
                    input_mode = True
                    if self.is_output(str(x)):
                        # 如果len(str(x)) > 1 说明是复制输入的
                        if len(str(x)) > 1:
                            data = x
                        match = self.vim_end_pattern.findall(self.vim_data)
                        if match:
                            if self.vim_flag or len(match) == 2:
                                self.vim_flag = False
                            else:
                                self.vim_flag = True
                        elif not self.vim_flag:
                            self.vim_flag = False
                            data = self.deal_command(data)[0:200]
                            if data is not None:
                                TtyLog(log=log,
                                       datetime=datetime.datetime.now(),
                                       cmd=data).save()
                        data = ''
                        self.vim_data = ''
                        input_mode = False

                    if len(x) == 0:
                        break
                    self.channel.send(x)

        finally:
            termios.tcsetattr(sys.stdin, termios.TCSADRAIN, old_tty)
            log_file_f.write('End time is %s' % datetime.datetime.now())
            log_file_f.close()
            log_time_f.close()
            termlog.save()
            log.filename = termlog.filename
            log.is_finished = True
            log.end_time = datetime.datetime.now()
            log.save()
Example #38
0
def init_key_read():
    old_settings = termios.tcgetattr(sys.stdin)
    tty.setcbreak(sys.stdin.fileno())
    return old_settings
 def __enter__(self):
     self.old_settings = termios.tcgetattr(sys.stdin)
     tty.setcbreak(sys.stdin.fileno()
                   )  # sys.stdin.fileno() == 0 ( stdout == 1, stderr == 2)
     return self
Example #40
0
Reckoning_list = []  #defining a list to use later
Inverse_list = []
apple = microsoft = quit = False  #set all variables to not read until called
print "Input your list using the [W, A, S, D, Q, E, Z, X] keys, then hit '1':"

try:  #if running on apple
    import sys, tty, termios  #imports for no return command
    fd = sys.stdin.fileno()  #unix file descriptor to define the file type
    old_settings = termios.tcgetattr(
        fd)  #records the existing console settings
    tty.setcbreak(sys.stdin)  #sets the style of input
    apple = True  #computer type

except:  #if running on microsoft
    import msvcrt  #microsoft file for key input
    microsoft = True  #computer typeprint

while quit == False:
    if microsoft == True:
        key = msvcrt.getch()  #format the keys into readable characters
    elif apple == True:
        key = sys.stdin.read(
            1
        )  #reads one character of input without requiring a return command

#############################################################################################
######### Create the initial input list
#############################################################################################

    for i in range(0, 1):  #only records one step
        Reckoning_list.insert(i, key.upper())
Example #41
0
def main():
    global KEY_PRESSED
    source = open('FlappyBird/scores', 'r')
    records = source.readlines()
    source.close()
    SCORE = 0
    STEP = 0.1
    GRAVITY = Vector(0, 1)
    KEY_STRENGHT = Vector(0, -3.5)
    TERMINAL_SIZE = Vector(79, 25)

    BG = (" " * TERMINAL_SIZE.x + "\n") * TERMINAL_SIZE.y
    TUBES = list()
    GROUND = ("=" * TERMINAL_SIZE.x + "\n") + \
        ("." * TERMINAL_SIZE.x + "\n") * 3
    GROUND = Sprite(GROUND)
    GROUND.pos = Vector(0, 21)
    BIRD = Sprite(("== (.\n \___\\", " / (./\n===_/"))
    BIRD.pos = Vector(10, 0)

    t = 0

    while True:
        fd = sys.stdin.fileno()
        old_settings = termios.tcgetattr(sys.stdin)
        tty.setcbreak(sys.stdin.fileno())

        t += 1
        time.sleep(STEP)
        if is_data():
            ch = sys.stdin.read(1)
            if ch == " ":
                KEY_PRESSED = True
        #else:
        #print("false")

        # if this setence in the game over, graph not right
        termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)

        # tubes
        if fmod(t, 51) == 0 or t == 1:
            pipe_height = randint(1, 7)
            up = Sprite("|      |\n" * pipe_height + "--------\n--------")
            up.pos = Vector(TERMINAL_SIZE.x, 0)
            TUBES.append(up)
            dn = Sprite("--------\n" * 2 + "|      |\n" * (8 - pipe_height))
            dn.shape = dn.shape[:-1]  # remove last \n
            dn.pos = Vector(TERMINAL_SIZE.x,
                            TERMINAL_SIZE.y + pipe_height - 8 - 6)
            TUBES.append(dn)
            TUBES = [x for x in TUBES if x.pos.x > -7]  # cleanup
        f = Vector(-1, 0)
        for x in TUBES:
            x.simulate([f], max_speed=1)

        # bird
        BIRD.simulate([GRAVITY])
        if KEY_PRESSED:
            KEY_PRESSED = False
            BIRD.vel = KEY_STRENGHT
            BIRD.simulate(max_speed=25)

        # score
        for x in TUBES:
            if x.pos.x == BIRD.pos.x - 9:
                SCORE += 0.5  # each tube
        SCORE = int(SCORE)

        # draw
        frame = GROUND.draw(BG)
        for x in TUBES:
            frame = x.draw(frame)
        s = Sprite(" SCORE: " + str(SCORE) + " ")
        s.pos = Vector(60, 23)
        docs = Sprite(" PRESS <SPACEBAR> ")
        docs.pos = Vector(5, 23)
        for x in (s, docs):
            frame = x.draw(frame)
        print(BIRD.draw(frame))

        # collisions
        colliders = list(TUBES)
        colliders.append(GROUND)
        if BIRD.collide(colliders) or BIRD.pos.y < 0:
            # game over
            print((" " * TERMINAL_SIZE.x + "\n") * TERMINAL_SIZE.y)
            print("GAME OVER")
            print("SCORE:", SCORE)
            records.append(SCORE)
            source = open('FlappyBird/scores', 'w')
            write_list(records, source)
            source.close()
            return
Example #42
0
 def begin(self):
     self.tattr = termios.tcgetattr(sys.stdin.fileno())
     if IS_UPY:
         termios.setraw(sys.stdin.fileno())
     else:
         tty.setcbreak(sys.stdin.fileno(), termios.TCSANOW)
Example #43
0
    def posix_shell(self):
        """
        Use paramiko channel connect server interactive.
        使用paramiko模块的channel,连接后端,进入交互式
        """
        log_file_f, log_time_f, log = self.get_log()
        old_tty = termios.tcgetattr(sys.stdin)
        pre_timestamp = time.time()
        data = ''
        input_mode = False
        try:
            tty.setraw(sys.stdin.fileno())
            tty.setcbreak(sys.stdin.fileno())
            self.channel.settimeout(0.0)

            while True:
                try:
                    r, w, e = select.select([self.channel, sys.stdin], [], [])
                    flag = fcntl.fcntl(sys.stdin, fcntl.F_GETFL, 0)
                    fcntl.fcntl(sys.stdin.fileno(), fcntl.F_SETFL,
                                flag | os.O_NONBLOCK)
                except Exception:
                    pass

                if self.channel in r:
                    try:
                        x = self.channel.recv(10240)
                        if len(x) == 0:
                            break
                        if self.vim_flag:
                            self.vim_data += x
                        index = 0
                        len_x = len(x)
                        while index < len_x:
                            try:
                                n = os.write(sys.stdout.fileno(), x[index:])
                                sys.stdout.flush()
                                index += n
                            except OSError as msg:
                                if msg.errno == errno.EAGAIN:
                                    continue
                        #sys.stdout.write(x)
                        #sys.stdout.flush()
                        now_timestamp = time.time()
                        log_time_f.write(
                            '%s %s\n' %
                            (round(now_timestamp - pre_timestamp, 4), len(x)))
                        log_time_f.flush()
                        log_file_f.write(x)
                        log_file_f.flush()
                        pre_timestamp = now_timestamp
                        log_file_f.flush()

                        if input_mode and not self.is_output(x):
                            data += x

                    except socket.timeout:
                        pass

                if sys.stdin in r:
                    try:
                        x = os.read(sys.stdin.fileno(), 4096)
                    except OSError:
                        pass
                    input_mode = True
                    if str(x) in ['\r', '\n', '\r\n']:
                        if self.vim_flag:
                            match = self.ps1_pattern.search(self.vim_data)
                            if match:
                                self.vim_flag = False
                                data = self.deal_command(data)[0:200]
                                if len(data) > 0:
                                    TtyLog(log=log,
                                           datetime=datetime.datetime.now(),
                                           cmd=data).save()
                        else:
                            data = self.deal_command(data)[0:200]
                            if len(data) > 0:
                                TtyLog(log=log,
                                       datetime=datetime.datetime.now(),
                                       cmd=data).save()
                        data = ''
                        self.vim_data = ''
                        input_mode = False

                    if len(x) == 0:
                        break
                    self.channel.send(x)

        finally:
            termios.tcsetattr(sys.stdin, termios.TCSADRAIN, old_tty)
            log_file_f.write('End time is %s' % datetime.datetime.now())
            log_file_f.close()
            log_time_f.close()
            log.is_finished = True
            log.end_time = datetime.datetime.now()
            log.save()
Example #44
0
File: channel.py Project: zkrx/tbot
    def attach_interactive(self,
                           end_magic: typing.Union[str, bytes,
                                                   None] = None) -> None:
        """
        Connect tbot's terminal to this channel.

        Allows the user to interact directly with whatever this channel is
        connected to.

        :param str, bytes end_magic: String that, when detected, should end the
            interactive session.  If no ``end_magic`` is given, pressing
            ``CTRL-D`` will terminate the session.
        """
        end_magic_bytes = (end_magic.encode("utf-8") if isinstance(
            end_magic, str) else end_magic)

        end_ring_buffer: typing.Deque[int] = collections.deque(
            maxlen=len(end_magic_bytes) if end_magic_bytes is not None else 1)

        # During an interactive session, the blacklist should not apply
        old_blacklist = self._write_blacklist
        self._write_blacklist = []

        previous: typing.Deque[int] = collections.deque(maxlen=3)

        oldtty = termios.tcgetattr(sys.stdin)
        try:
            tty.setraw(sys.stdin.fileno())
            tty.setcbreak(sys.stdin.fileno())

            mode = termios.tcgetattr(sys.stdin)
            special_chars = mode[6]
            assert isinstance(special_chars, list)
            special_chars[termios.VMIN] = b"\0"
            special_chars[termios.VTIME] = b"\0"
            termios.tcsetattr(sys.stdin, termios.TCSAFLUSH, mode)

            while True:
                r, _, _ = select.select([self, sys.stdin], [], [])

                if self in r:
                    data = self._c.read(4096)
                    if isinstance(end_magic_bytes, bytes):
                        end_ring_buffer.extend(data)
                        for a, b in itertools.zip_longest(
                                end_ring_buffer, end_magic_bytes):
                            if a != b:
                                break
                        else:
                            break
                    sys.stdout.buffer.write(data)
                    sys.stdout.buffer.flush()
                if sys.stdin in r:
                    data = sys.stdin.buffer.read(4096)
                    previous.extend(data)
                    if end_magic is None and data == b"\x04":
                        break
                    for a, b in itertools.zip_longest(previous, b"\r~."):
                        if a != b:
                            break
                    else:
                        break
                    self.send(data)

            sys.stdout.write("\r\n")
        finally:
            self._write_blacklist = old_blacklist
            termios.tcsetattr(sys.stdin, termios.TCSADRAIN, oldtty)
Example #45
0
def main(args):
    def is_data():
        return select.select([sys.stdin], [], [], 0) == ([sys.stdin], [], [])

    print('Python version:', sys.version)
    print('')
    print('Running on:')
    print(os.getcwd())

    rx = Rot.from_euler('x', 5, degrees=True)
    ry = Rot.from_euler('y', 5, degrees=True)
    rz = Rot.from_euler('z', 5, degrees=True)

    step = 0.01  # 1cm
    old_settings = termios.tcgetattr(sys.stdin)
    rospy.init_node("ur_kinematics", anonymous=False, disable_signals=True)

    kin = URKinematics(args)

    try:
        tty.setcbreak(sys.stdin.fileno())
        rospy.loginfo('Kinematics test.')
        rospy.loginfo('Press: ')
        rospy.loginfo('qa->z ws->x  ed->y')
        rospy.loginfo('t -> stop')
        rospy.loginfo('p -> current pose')
        rospy.loginfo('ESC to exit.')

        while not rospy.is_shutdown():

            if is_data():

                joints = kin.joints_state
                pos = kin.fwd_kin(joints, i_unit='r', o_unit='p')
                r = Rot.from_quat([
                    pos.orientation.x, pos.orientation.y, pos.orientation.z,
                    pos.orientation.w
                ], True)

                c = sys.stdin.read(1)

                if c == '\x1b': break  # x1b is ESC
                if c == 'q': pos.position.z += step
                if c == 'a': pos.position.z -= step
                if c == 'w': pos.position.x += step
                if c == 's': pos.position.x -= step
                if c == 'e': pos.position.y += step
                if c == 'd': pos.position.y -= step
                if c == '1': r = r * rx
                if c == '7': r = r * rx.inv()
                if c == '2': r = r * ry
                if c == '8': r = r * ry.inv()
                if c == '3': r = r * rz
                if c == '9': r = r * rz.inv()
                if c == 'p': print(pos)

                r = r.as_quat()
                pos.orientation.x = r[0]
                pos.orientation.y = r[1]
                pos.orientation.z = r[2]
                pos.orientation.w = r[3]
                kin.movel(pos)
                # time.sleep(0.1)

                if c == 't': kin.go_to_and_wait('stop')
                if c == 'l': kin.go_to_and_wait('drop')

                if c == 'z':
                    kin.movel([0.25, 0.0, 0.1])
                    kin.movel([0.25, 0.0, 0.0], speed=0.1)
                if c == 'b':
                    os.chdir('/home/ubuntu/ur_ws/src/integrator/config')
                    with open('coordinates.yaml') as file:
                        data = yaml.load(file, Loader=yaml.FullLoader)
                        a = data['coord_a'][0]
                        b = data['coord_a'][1]
                        c = data['coord_d'][0]
                        d = data['coord_d'][1]

                    coord_a = [a, b, 0.06]
                    coord_a_ = [a, b, 0.05]
                    coord_b = [a, d, 0.06]
                    coord_b_ = [a, d, 0.05]
                    coord_c = [c, b, 0.06]
                    coord_c_ = [c, b, 0.05]
                    coord_d = [c, d, 0.06]
                    coord_d_ = [c, d, 0.05]

                    kin.movel(coord_b, speed=0.1)
                    # input('pause')
                    kin.movel(coord_b_, speed=0.1)
                    # input('pause')
                    kin.movel(coord_b, speed=0.1)
                    kin.movel(coord_a, speed=0.1)
                    kin.movel(coord_a_, speed=0.1)
                    kin.movel(coord_a, speed=0.1)
                    # kin.movel(coord_b, speed=0.1)
                    kin.movel(coord_c, speed=0.1)
                    kin.movel(coord_c_, speed=0.1)
                    kin.movel(coord_c, speed=0.1)

                    kin.movel(coord_d, speed=0.1)
                    kin.movel(coord_d_, speed=0.1)
                    kin.movel(coord_d, speed=0.1)

                    # kin.movel(coord_a, speed=0.1)
                    kin.movel([a, d, 0.1], speed=0.1)
                    # kin.go_to_and_wait('stop')
                if c == 'c':
                    x = float(input('Enter x: '))
                    y = float(input('Enter y: '))
                    z = float(input('Enter z: '))
                    point = kin.check_working_space([[x, y, z]])
                    if len(point) == 0:
                        rospy.logerr('Position out of reach')
                    else:
                        kin.movel(*point)
                if c == 'j':
                    print(kin.joints_state)

    finally:
        termios.tcsetattr(sys.stdin, termios.TCSADRAIN, old_settings)
        kin.send_goal('stop')
        rospy.loginfo("Position stop")
        try:
            kin.wait_for_result(rospy.Duration(3))
        except KeyboardInterrupt:
            kin.cancel_goal()
            raise
Example #46
0
    def run(self):
        print_status("Running module")

        client = paramiko.SSHClient()
        client.set_missing_host_key_policy(paramiko.AutoAddPolicy())

        try:
            client.connect(self.target,
                           username='',
                           allow_agent=False,
                           look_for_keys=False)
        except paramiko.ssh_exception.SSHException:
            pass

        trans = client.get_transport()
        try:
            trans.auth_password(username='******',
                                password='',
                                event=None,
                                fallback=True)
        except paramiko.ssh_exception.AuthenticationException:
            pass
        except:
            print_status("Error with Existing Session. Wait few minutes.")
            return

        try:
            trans.auth_interactive(username='******',
                                   handler=self.custom_handler)
            chan = client.invoke_shell()
        except:
            print_error("Exploit failed")
            return

        print_success("Exploit succeeded")
        oldtty = termios.tcgetattr(sys.stdin)
        try:
            tty.setraw(sys.stdin.fileno())
            tty.setcbreak(sys.stdin.fileno())
            chan.settimeout(0.0)

            while True:
                r, w, e = select.select([chan, sys.stdin], [], [])
                if chan in r:
                    try:
                        x = u(chan.recv(1024))
                        if len(x) == 0:
                            sys.stdout.write('\r\n*** EOF\r\n')
                            break
                        sys.stdout.write(x)
                        sys.stdout.flush()
                    except socket.timeout:
                        pass
                if sys.stdin in r:
                    x = sys.stdin.read(1)
                    if len(x) == 0:
                        break
                    chan.send(x)

        finally:
            termios.tcsetattr(sys.stdin, termios.TCSADRAIN, oldtty)
Example #47
0
def main():

    sequences = []
    pexit = False  # Exit condition, never set to true. For future devel.

    # Init the connection
    r2d2, ble = r2d2_init()

    # Start reading the pad
    tty.setcbreak(sys.stdin)

    # Control loop
    while pexit == False:
        # Get the scancode from the mapped pad
        scancode = ord(sys.stdin.read(1))
        # In case of wrong scancode, command is set to False
        valid_command = True

        # Create the commands sequence
        if scancode == 65:  # Up
            sequences.append(commandmap["tripod"])
            sequences.append(commandmap["yes"])
        elif scancode == 66:  # Down
            sequences.append(commandmap["bipod"])
            sequences.append(commandmap["yes"])
        elif scancode == 67:  # Rot left
            sequences.append(commandmap["rot0"])
            sequences.append(commandmap["no"])
        elif scancode == 68:  # Rot right
            sequences.append(commandmap["rot+"])
            sequences.append(commandmap["surprise"])
        elif scancode == 122:  # Button 3, 4
            sequences.append(commandmap["laugh"])
            sequences.append(commandmap["happy"])
            sequences.append(commandmap["excited"])
        elif scancode == 32:  # Button 5
            sequences.append(commandmap["surprise"])
            sequences.append(commandmap["sad"])
            sequences.append(commandmap["scared"])
        elif scancode == 120:  # Button 6
            sequences.append(commandmap["confident"])
            sequences.append(commandmap["laugh2"])
        elif scancode == 105:  # Front left
            sequences.append(commandmap["angry"])
            sequences.append(commandmap["alarm"])
        elif scancode == 111:  # Front right
            sequences.append(commandmap["chatty"])
            sequences.append(commandmap["ionblast"])
        else:
            valid_command = False

        # Executes the command sequence
        if valid_command == True:
            for seq in sequences:
                #device.char_write_handle(0x1c, commandmap[command], True)
                r2d2.char_write_handle(0x1c, BuildPacket(seq), True)

        # Empty the sequence list
        del sequences[:]

    ble.stop()
Example #48
0
    def _open_posix_shell(self, channel, key_handlers, handle_window_size):
        # We need to make sure to use an unbuffered stdin, else multi-byte
        # chars (such as arrow keys) won't work properly.
        with os.fdopen(sys.stdin.fileno(), 'r', 0) as stdin:
            oldtty = termios.tcgetattr(stdin)

            # Update the terminal size whenever the size changes.
            if handle_window_size:

                def handle_sigwinch(signum, frame):
                    rows, cols = get_terminal_size()
                    self._set_terminal_size(rows, cols)

                signal.signal(signal.SIGWINCH, handle_sigwinch)
                handle_sigwinch(None, None)

            # Read from stdin and write to the network, endlessly.
            try:
                tty.setraw(sys.stdin.fileno())
                tty.setcbreak(sys.stdin.fileno())
                channel.settimeout(0.0)

                while True:
                    try:
                        r, w, e = select.select([channel, stdin], [], [])
                    except select.error as e:
                        code, message = e
                        if code == errno.EINTR:
                            # This may happen when SIGWINCH is called
                            # during the select; we just retry then.
                            continue
                        raise

                    if channel in r:
                        try:
                            data = channel.recv(1024)
                        except socket.timeout:
                            pass
                        if not data:
                            self._dbg(1, 'EOF from remote')
                            break
                        self._receive_cb(data, False)
                        self.buffer.append(data)
                    if stdin in r:
                        data = stdin.read(1)
                        self.buffer.clear()
                        if len(data) == 0:
                            break

                        # Temporarily revert stdin behavior while callbacks are
                        # active.
                        curtty = termios.tcgetattr(stdin)
                        termios.tcsetattr(stdin, termios.TCSADRAIN, oldtty)
                        is_handled = self._call_key_handlers(
                            key_handlers, data)
                        termios.tcsetattr(stdin, termios.TCSADRAIN, curtty)

                        if not is_handled:
                            if not self.send_data is None:
                                self.send_data.write(data)
                            channel.send(data)
            finally:
                termios.tcsetattr(stdin, termios.TCSADRAIN, oldtty)
 def nbTerm(self):
     '''
     Sets up the terminal for non-blocking input
     '''
     tty.setcbreak(sys.stdin.fileno())
Example #50
0
 def connect_motor_setting(self):
     self.ser = serial.Serial('/dev/ttyACM0', 9600)
     self.old_settings = termios.tcgetattr(sys.stdin)
     tty.setcbreak(sys.stdin.fileno())
     if (self.ser.isOpen()):
         self.print_msg("Motor Connect")
 def __enter__(self):
     self.original_stty = termios.tcgetattr(self.stream)
     tty.setcbreak(self.stream)
Example #52
0
def main():
    ssh = paramiko.SSHClient()
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    ssh.connect('xxx.xx.xx.xx', username='******', password='******')

    tran = ssh.get_transport()
    chan = tran.open_session()

    chan.get_pty()
    chan.invoke_shell()

    logging.basicConfig(
        level=logging.DEBUG,
        format=
        '%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s',
        datefmt='%a, %d %b %Y %H:%M:%S',
        filename='test.log',
        filemode='w')

    oldtty = termios.tcgetattr(sys.stdin)
    try:
        tty.setraw(sys.stdin.fileno())
        tty.setcbreak(sys.stdin.fileno())
        chan.settimeout(0.0)
        command = ''
        command_history = []
        tab = False
        up_tag = False
        down_tag = False
        while True:
            r, w, e = select.select([chan, sys.stdin], [], [])
            wat = fcntl.ioctl(r[0].fileno(), termios.FIONREAD, "  ")
            doublewat = struct.unpack('h', wat)[0]
            if chan in r:
                try:
                    recv_data = u(chan.recv(1024))
                    if len(recv_data) == 0:
                        sys.stdout.write("\r\n*** EOF\r\n")
                        break
                    if len(recv_data) == 1:
                        if recv_data in '\x07':
                            recv_data = recv_data.replace('\x07', '')
                        if recv_data:
                            command += recv_data
                            logging.warn("accept one char command:" + command +
                                         "<--------------")
                    else:
                        if up_tag or down_tag:
                            command = recv_data
                            logging.debug("recv_data:" + recv_data +
                                          "..............")
                        else:
                            if '[' not in recv_data and ']' not in recv_data:
                                if '\n' not in recv_data or '\r' not in recv_data:
                                    if tab:
                                        command += recv_data
                                    else:
                                        command = recv_data
                                    logging.error("command:" + str(tab) +
                                                  command + "<-------")
                    sys.stdout.write(recv_data)
                    sys.stdout.flush()
                except socket.timeout:
                    pass
            if sys.stdin in r:
                x = sys.stdin.read(doublewat)
                if len(x) == 0:
                    break
                chan.send(x)
                input_char = x
                if input_char == '\t':
                    tab = True
                if input_char == '\x1b[A':
                    logging.debug("you pressed up|")
                    up_tag = True
                elif input_char == '\x1b[B':
                    logging.debug("you pressed down")
                    down_tag = True
                if input_char == '\x7F':
                    if command:
                        command = command[:-1]
                if input_char == '\x0D':
                    if command.strip():
                        if '\x07' in command or '\x08' in command:
                            command = command.replace('\x07',
                                                      '').replace('\x08', '')
                        if '\r' or '\x1b[C' or '\x1b[K' in command:
                            command = command.replace('\r', '').replace(
                                '\x1b[C', '').replace('\x1b[K', '')
                        command_history.append(command)
                    command = ''
                    tab = False
                    up_tag = False
                    down_tag = False
                    logging.debug(command_history)

    finally:
        termios.tcsetattr(sys.stdin, termios.TCSADRAIN, oldtty)
        ssh.close()
Example #53
0
 def __init__(self):
     self.old_settings = termios.tcgetattr(sys.stdin)
     tty.setcbreak(sys.stdin.fileno())
Example #54
0
    def run(self):
        #initial values
        self.__board.printboard(0, 7, 3, 0, 0)

        speed = 2  #do not change
        previnp = "s"  #for jumping

        try:
            tty.setcbreak(sys.stdin.fileno())
            while (1):

                global mariopresent, marioprev, life, score, a, cjump, bullet, x, y, i, loop, loop2

                #if won
                if mariopresent == [33, 609]:
                    os.system('aplay ./sounds/smb_stage_clear.wav')
                    #spawn fireworks
                    for f in range(580, 650, 10):
                        self.__board.addfireworks(10, f)
                        os.system('clear')
                        self.__board.printboard(i, mariopresent[1], life,
                                                score, bullet)
                        #print(f)
                        os.system('aplay ./sounds/smb_fireworks.wav')
                        #time.sleep(.5)

                    time.sleep(2)
                    os.system('clear')
                    print("SCORE->", score)
                    time.sleep(1)
                    print("LIFE_SCORE->", life * 100)
                    time.sleep(1)
                    timescore = 0
                    if (time.time() - a) <= 100:
                        timescore = 100
                    if (time.time() - a) <= 150:
                        timescore = 50
                    print("TIME_SCORE->", timescore)
                    time.sleep(1)
                    print("TOTAL SCORE->", score + life * 100 + timescore)
                    time.sleep(1)
                    print("YOU WON")
                    time.sleep(1)
                    break
                    #game ends

                #check on jump
                low = 1

                #------------------------------keystroke dependent----------------------------------

                if isData():
                    # read input keystroke from user
                    keyStroke = sys.stdin.read(1)

                    #for bullets
                    if keyStroke == "f" and bullet == 1:
                        os.system('aplay ./sounds/smb_fireball.wav')

                        #checking directions
                        direction = 1  #if no previnp
                        if previnp == "d":
                            direction = 1
                        elif previnp == "a":
                            direction = -1

                        #range of bullet
                        for b in range(0, 11 * direction, direction):
                            g = self.__board.getgrid(
                                mariopresent[0] + 1, mariopresent[1] +
                                3 * direction + b)  #storing next cell
                            self.__board.fire1(
                                mariopresent[0] + 1,
                                mariopresent[1] + 3 * direction + b)
                            os.system('clear')
                            self.__board.printboard(i, mariopresent[1], life,
                                                    score, bullet)
                            self.__board.fire2(
                                mariopresent[0] + 1,
                                mariopresent[1] + 3 * direction + b, g)
                            time.sleep(.03)
                            os.system('clear')
                            self.__board.printboard(i, mariopresent[1], life,
                                                    score, bullet)

                            #check if enemy dead or not
                            if self.__board.getgrid(
                                    mariopresent[0] + 1, mariopresent[1] +
                                    3 * direction + b + direction) == "Q":
                                if self.__board.getgrid(
                                        mariopresent[0] + 1, mariopresent[1] +
                                        3 * direction + b + 2 * direction
                                ) != "Q":  #enemy2 cannot be killed
                                    self.__board.cleane1a(
                                        mariopresent[1] + 3 * direction + b +
                                        direction,
                                        enemy1[x.index(mariopresent[1] +
                                                       3 * direction + b +
                                                       direction), :])  #vanish
                                    #x[x.index(mariopresent[1]+3*direction+b+direction)]=-1#send back
                                    x.remove(mariopresent[1] + 3 * direction +
                                             b + direction)  #send back
                                score += 10

                            #check if bullet can move forward
                            if checkj(
                                    self.__board.getgrid(
                                        mariopresent[0] + 1, mariopresent[1] +
                                        3 * direction + b + direction),
                                    self.__board.getgrid(
                                        mariopresent[0] + 1, mariopresent[1] +
                                        3 * direction + b + direction)) == -1:
                                break

                    #moving forward
                    if keyStroke == "d" and mariopresent[1] < (i + 100 - 6):

                        #check obstacle
                        c1 = checkmv(
                            self.__board.getgrid(mariopresent[0] + 1,
                                                 mariopresent[1] + 4))
                        if c1:
                            self.__board.updateboardf(mariopresent, marioprev)

                            #updating prev array (writing forward bacause early depends on late)
                            marioprev[0] = self.__board.getgrid(
                                mariopresent[0], mariopresent[1] + 2)
                            marioprev[1] = marioprev[3]
                            marioprev[2] = marioprev[4]
                            marioprev[3] = marioprev[5]
                            marioprev[4] = self.__board.getgrid(
                                mariopresent[0] + 1, mariopresent[1] + 3)
                            marioprev[5] = self.__board.getgrid(
                                mariopresent[0] + 1, mariopresent[1] + 4)
                            marioprev[6] = marioprev[7]
                            marioprev[7] = self.__board.getgrid(
                                mariopresent[0] + 2, mariopresent[1] + 3)

                            #updating mario
                            mariopresent = [
                                mariopresent[0], mariopresent[1] + speed
                            ]

                            #check river
                            c2 = checkrv(
                                self.__board.getgrid(mariopresent[0] + 3,
                                                     mariopresent[1] - 1),
                                self.__board.getgrid(mariopresent[0] + 3,
                                                     mariopresent[1] + 1))

                            life += c2
                            self.__board.updatemario(mariopresent[0],
                                                     mariopresent[1])
                            previnp = "d"
                            os.system('clear')
                            self.__board.printboard(i, mariopresent[1], life,
                                                    score, bullet)

                            #if falls in river
                            if c2 == -1:
                                os.system('aplay ./sounds/smb_mariodie.wav')
                                screen.reset(self)

                    #moving backward
                    if keyStroke == "a" and mariopresent[1] > i + 6:

                        #checking obstacles
                        c1 = checkmv(
                            self.__board.getgrid(mariopresent[0] + 1,
                                                 mariopresent[1] - 4))
                        if c1:
                            self.__board.updateboardb(mariopresent, marioprev)

                            #updating prev array (writing backward because later depends on early)
                            marioprev[7] = marioprev[6]
                            marioprev[6] = self.__board.getgrid(
                                mariopresent[0] + 2, mariopresent[1] - 3)
                            marioprev[5] = marioprev[3]
                            marioprev[4] = marioprev[2]
                            marioprev[3] = marioprev[1]
                            marioprev[2] = self.__board.getgrid(
                                mariopresent[0] + 1, mariopresent[1] - 3)
                            marioprev[1] = self.__board.getgrid(
                                mariopresent[0] + 1, mariopresent[1] - 4)
                            marioprev[0] = self.__board.getgrid(
                                mariopresent[0], mariopresent[1] - 2)

                            #updating mario
                            mariopresent = [
                                mariopresent[0], mariopresent[1] - speed
                            ]
                            #river check
                            c2 = checkrv(
                                self.__board.getgrid(mariopresent[0] + 3,
                                                     mariopresent[1] - 1),
                                self.__board.getgrid(mariopresent[0] + 3,
                                                     mariopresent[1] + 1))

                            life += c2
                            self.__board.updatemario(mariopresent[0],
                                                     mariopresent[1])
                            previnp = "a"
                            os.system('clear')
                            self.__board.printboard(i, mariopresent[1], life,
                                                    score, bullet)

                            #if dead
                            if c2 == -1:
                                os.system('aplay ./sounds/smb_mariodie.wav')
                                screen.reset(self)

                    #jumps to height +10
                    if keyStroke == "w":

                        #moving up
                        timer = 5
                        while (timer != 0):
                            time.sleep(.01)

                            #checks if can move up
                            c3 = checkj(
                                self.__board.getgrid(mariopresent[0] - 2,
                                                     mariopresent[1] + 1),
                                self.__board.getgrid(mariopresent[0] - 2,
                                                     mariopresent[1] - 1))
                            if c3 == -1:
                                djump = 0
                                break
                            else:
                                djump = 1

                            self.__board.updateboardbup(
                                mariopresent, marioprev)

                            #updating prev array
                            marioprev[0] = self.__board.getgrid(
                                mariopresent[0] - 2, mariopresent[1])
                            marioprev[1] = self.__board.getgrid(
                                mariopresent[0] - 1, mariopresent[1] - 2)
                            marioprev[2] = self.__board.getgrid(
                                mariopresent[0] - 1, mariopresent[1] - 1)
                            marioprev[3] = self.__board.getgrid(
                                mariopresent[0] - 1, mariopresent[1])
                            marioprev[4] = self.__board.getgrid(
                                mariopresent[0] - 1, mariopresent[1] + 1)
                            marioprev[5] = self.__board.getgrid(
                                mariopresent[0] - 1, mariopresent[1] + 2)
                            marioprev[6] = self.__board.getgrid(
                                mariopresent[0], mariopresent[1] - 1)
                            marioprev[7] = self.__board.getgrid(
                                mariopresent[0], mariopresent[1] + 1)

                            mariopresent = [
                                mariopresent[0] - speed, mariopresent[1]
                            ]
                            self.__board.updatemario(mariopresent[0],
                                                     mariopresent[1])
                            timer -= 1
                            os.system('clear')
                            self.__board.printboard(i, mariopresent[1], life,
                                                    score, bullet)

                        #moving right
                        if previnp == "d" and (mariopresent[1] + 14) < (i +
                                                                        100):

                            #16 units to right
                            timer = 8
                            while (timer != 0):
                                time.sleep(.01)
                                self.__board.updateboardf(
                                    mariopresent, marioprev)

                                #updating prev array (writing forward bacause early depends on late)
                                marioprev[0] = self.__board.getgrid(
                                    mariopresent[0], mariopresent[1] + 2)
                                marioprev[1] = marioprev[3]
                                marioprev[2] = marioprev[4]
                                marioprev[3] = marioprev[5]
                                marioprev[4] = self.__board.getgrid(
                                    mariopresent[0] + 1, mariopresent[1] + 3)
                                marioprev[5] = self.__board.getgrid(
                                    mariopresent[0] + 1, mariopresent[1] + 4)
                                marioprev[6] = marioprev[7]
                                marioprev[7] = self.__board.getgrid(
                                    mariopresent[0] + 2, mariopresent[1] + 3)

                                mariopresent = [
                                    mariopresent[0], mariopresent[1] + speed
                                ]
                                self.__board.updatemario(
                                    mariopresent[0], mariopresent[1])
                                timer -= 1
                                os.system('clear')
                                self.__board.printboard(
                                    i, mariopresent[1], life, score, bullet)

                        #moving left
                        if previnp == "a" and (mariopresent[1] - 14) > (i + 6):

                            #16 units to left
                            timer = 8
                            while (timer != 0):
                                time.sleep(.01)
                                self.__board.updateboardb(
                                    mariopresent, marioprev)

                                #updating prev array (writing backward because later depends on early)
                                marioprev[7] = marioprev[6]
                                marioprev[6] = self.__board.getgrid(
                                    mariopresent[0] + 2, mariopresent[1] - 3)
                                marioprev[5] = marioprev[3]
                                marioprev[4] = marioprev[2]
                                marioprev[3] = marioprev[1]
                                marioprev[2] = self.__board.getgrid(
                                    mariopresent[0] + 1, mariopresent[1] - 3)
                                marioprev[1] = self.__board.getgrid(
                                    mariopresent[0] + 1, mariopresent[1] - 4)
                                marioprev[0] = self.__board.getgrid(
                                    mariopresent[0], mariopresent[1] - 2)

                                mariopresent = [
                                    mariopresent[0], mariopresent[1] - speed
                                ]
                                self.__board.updatemario(
                                    mariopresent[0], mariopresent[1])

                                timer -= 1
                                os.system('clear')
                                self.__board.printboard(
                                    i, mariopresent[1], life, score, bullet)

                        #moving down
                        timer = 4
                        while (timer != 0 and djump == 1):

                            #check if it can move down
                            c3 = checkj(
                                self.__board.getgrid(mariopresent[0] + 3,
                                                     mariopresent[1] + 1),
                                self.__board.getgrid(mariopresent[0] + 3,
                                                     mariopresent[1] - 1))
                            if c3 == -1:
                                break

                            #surprise coins
                            if mariopresent[1] == 75 and mariopresent[
                                    0] == 23 and cjump > 0:
                                cjump -= 1
                                self.__board.jumpupc(24, 75)
                                os.system('clear')
                                self.__board.printboard(
                                    i, mariopresent[1], life, score, bullet)
                                time.sleep(.2)
                                self.__board.updatecell(21, 75, "-")
                                self.__board.updatecell(22, 75, "O")
                                score += 1

                            time.sleep(.06)
                            self.__board.updateboardbdown(
                                mariopresent, marioprev)
                            #updating pre array
                            marioprev[0] = self.__board.getgrid(
                                mariopresent[0] + 2, mariopresent[1])
                            marioprev[1] = self.__board.getgrid(
                                mariopresent[0] + 3, mariopresent[1] - 2)
                            marioprev[2] = self.__board.getgrid(
                                mariopresent[0] + 3, mariopresent[1] - 1)
                            marioprev[3] = self.__board.getgrid(
                                mariopresent[0] + 3, mariopresent[1])
                            marioprev[4] = self.__board.getgrid(
                                mariopresent[0] + 3, mariopresent[1] + 1)
                            marioprev[5] = self.__board.getgrid(
                                mariopresent[0] + 3, mariopresent[1] + 2)
                            marioprev[6] = self.__board.getgrid(
                                mariopresent[0] + 4, mariopresent[1] - 1)
                            marioprev[7] = self.__board.getgrid(
                                mariopresent[0] + 4, mariopresent[1] + 1)

                            mariopresent = [
                                mariopresent[0] + speed, mariopresent[1]
                            ]
                            self.__board.updatemario(mariopresent[0],
                                                     mariopresent[1])
                            timer -= 1
                            os.system('clear')
                            self.__board.printboard(i, mariopresent[1], life,
                                                    score, bullet)

                        previnp = "w"

                    if keyStroke == "q":
                        break
                    #for straight jump
                    if keyStroke not in ["a", "w", "d", "q", "f"]:
                        previnp = "s"

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

#---------------------------keystroke independent process------------------------------

#if already climbed an object check to move it down
#whenever normal jump not there this code will be executed
                while low:

                    #check for end flag
                    if self.__board.getgrid(
                            mariopresent[0] + 3, mariopresent[1] -
                            1) == "M" and self.__board.getgrid(
                                mariopresent[0] + 3, mariopresent[1] +
                                1) == "M" and mariopresent[0] < 25:
                        os.system('aplay ./sounds/smb_flagpole.wav')
                        fi = 20
                        while (fi != 33):
                            self.__board.moveflag(fi)
                            fi += 1
                            time.sleep(.03)
                            os.system('clear')
                            self.__board.printboard(i, mariopresent[1], life,
                                                    score, bullet)

                    #to move down
                    temp = ["-", "/"]
                    if self.__board.getgrid(
                            mariopresent[0] + 3, mariopresent[1] -
                            1) in temp and self.__board.getgrid(
                                mariopresent[0] + 3, mariopresent[1] +
                                1) in temp and self.__board.getgrid(
                                    mariopresent[0] + 3,
                                    mariopresent[1]) in temp:

                        #check for bullet power up
                        if mariopresent[0] == 29 and mariopresent[1] in [
                                51, 215, 216, 217, 218, 219
                        ]:
                            self.__board.addflower(25, mariopresent[1])

                        #coins
                        if self.__board.getgrid(mariopresent[0] - 1,
                                                mariopresent[1]) == "O":
                            ts = score
                            score += self.__board.jumpupc(
                                mariopresent[0] - 1, mariopresent[1])
                            #powerup check
                            p = 0
                            if score - ts == 11:
                                p = 1
                            #time.sleep(0.1)
                            os.system('clear')
                            self.__board.printboard(i, mariopresent[1], life,
                                                    score, bullet)
                            time.sleep(0.1)
                            self.__board.jumpdownc(mariopresent[0] - 1,
                                                   mariopresent[1])
                            if p == 1:
                                self.__board.powerup(mariopresent[0] - 1,
                                                     mariopresent[1])
                            #time.sleep(0.1)
                            os.system('clear')
                            self.__board.printboard(i, mariopresent[1], life,
                                                    score, bullet)
                        """
                        c3=checkj(self.__board.getgrid(mariopresent[0]+3,mariopresent[1]+1),self.__board.getgrid(mariopresent[0]+3,mariopresent[1]-1))
                        if c3==-1:
                            break 
                        """

                        low = 1
                        time.sleep(.06)
                        self.__board.updateboardbdown(mariopresent, marioprev)
                        #updating pre array
                        marioprev[0] = self.__board.getgrid(
                            mariopresent[0] + 2, mariopresent[1])
                        marioprev[1] = self.__board.getgrid(
                            mariopresent[0] + 3, mariopresent[1] - 2)
                        marioprev[2] = self.__board.getgrid(
                            mariopresent[0] + 3, mariopresent[1] - 1)
                        marioprev[3] = self.__board.getgrid(
                            mariopresent[0] + 3, mariopresent[1])
                        marioprev[4] = self.__board.getgrid(
                            mariopresent[0] + 3, mariopresent[1] + 1)
                        marioprev[5] = self.__board.getgrid(
                            mariopresent[0] + 3, mariopresent[1] + 2)
                        marioprev[6] = self.__board.getgrid(
                            mariopresent[0] + 4, mariopresent[1] - 1)
                        marioprev[7] = self.__board.getgrid(
                            mariopresent[0] + 4, mariopresent[1] + 1)

                        mariopresent = [
                            mariopresent[0] + speed, mariopresent[1]
                        ]
                        self.__board.updatemario(mariopresent[0],
                                                 mariopresent[1])
                        self.__board.printboard(i, mariopresent[1], life,
                                                score, bullet)

                    #kill enemy by jumping
                    elif self.__board.getgrid(
                            mariopresent[0] + 3, mariopresent[1] -
                            1) == "Q" or self.__board.getgrid(
                                mariopresent[0] + 3, mariopresent[1] +
                                1) == "Q" or self.__board.getgrid(
                                    mariopresent[0] + 3,
                                    mariopresent[1]) == "Q":
                        low = 1
                        print("EFEFEF")
                        score += 20
                        if self.__board.getgrid(mariopresent[0] + 3,
                                                mariopresent[1] - 1) == "Q":
                            if self.__board.getgrid(
                                    mariopresent[0] + 3, mariopresent[1] -
                                    2) != "Q" and self.__board.getgrid(
                                        mariopresent[0] + 3,
                                        mariopresent[1]) != "Q":  #enemy2 check
                                os.system('aplay ./sounds/smb_stomp.wav')
                                self.__board.cleane1a(
                                    mariopresent[1] - 1,
                                    enemy1[x.index(mariopresent[1] - 1), :])
                                #x[x.index(mariopresent[1]-1)]=-1#send back
                                x.remove(mariopresent[1] - 1)  #send back
                            #if enemy2 then dead
                            else:
                                life -= 1
                                os.system('aplay ./sounds/smb_mariodie.wav')
                                screen.reset(self)

                        elif self.__board.getgrid(mariopresent[0] + 3,
                                                  mariopresent[1] + 1) == "Q":
                            if self.__board.getgrid(
                                    mariopresent[0] + 3, mariopresent[1] +
                                    2) != "Q" and self.__board.getgrid(
                                        mariopresent[0] + 3,
                                        mariopresent[1]) != "Q":
                                os.system('aplay ./sounds/smb_stomp.wav')
                                self.__board.cleane1a(
                                    mariopresent[1] + 1,
                                    enemy1[x.index(mariopresent[1] + 1), :])
                                #x[x.index(mariopresent[1]+1)]=-1#send back
                                x.remove(mariopresent[1] + 1)  #send back
                            #if enemy2 then dead
                            else:
                                life -= 1
                                os.system('aplay ./sounds/smb_mariodie.wav')
                                screen.reset(self)

                        else:
                            if self.__board.getgrid(
                                    mariopresent[0] + 3, mariopresent[1] +
                                    1) != "Q" and self.__board.getgrid(
                                        mariopresent[0] + 3,
                                        mariopresent[1] - 1) != "Q":
                                os.system('aplay ./sounds/smb_stomp.wav')
                                self.__board.cleane1a(
                                    mariopresent[1],
                                    enemy1[x.index(mariopresent[1]), :])
                                #x[x.index(mariopresent[1])]=-1#send back
                                x.remove(mariopresent[1])  #send back
                            #if enemy2 then dead
                            else:
                                life -= 1
                                os.system('aplay ./sounds/smb_mariodie.wav')
                                screen.reset(self)

                    else:
                        low = 0
                        c2 = checkrv(
                            self.__board.getgrid(mariopresent[0] + 3,
                                                 mariopresent[1] - 1),
                            self.__board.getgrid(mariopresent[0] + 3,
                                                 mariopresent[1] + 1))
                        life += c2
                        if c2 == -1:
                            os.system('aplay ./sounds/smb_mariodie.wav')
                            screen.reset(self)

                if 1:

                    #FOR SCREEN
                    if mariopresent[1] > (
                            i + 50):  #position of mario at which screen moves
                        i += 20
                        #time.sleep(0.03)
                        os.system('clear')
                        self.__board.printboard(i, mariopresent[1], life,
                                                score, bullet)

                    #array of enemies
                    #enemies completely governed by these arrays
                    x, y = self.__board.searchenemy(i)

                    #check for powerups
                    if self.__board.getgrid(mariopresent[0] + 2,
                                            mariopresent[1]) == "P":
                        os.system('aplay ./sounds/smb_1-up.wav')
                        life += 1
                        self.__board.updatecell(mariopresent[0] + 2,
                                                mariopresent[1], "-")

                    #check for flower
                    if marioprev[3] == 'I':
                        os.system('aplay ./sounds/smb_powerup.wav')
                        marioprev[3] = "-"
                        bullet = 1

                    #speed increase as mario progresses
                    if mariopresent[1] > 350:
                        check = .7
                    else:
                        check = 1

                    if time.time() - loop > check:
                        loop = time.time()
                        #FOR ENEMY1
                        if len(x) != 0 and i + 100 > x[len(x) - 1] > i:
                            for count in range(len(x)):
                                if mariopresent[1] < x[count]:
                                    c1 = checkmv(
                                        self.__board.getgrid(35, x[count] - 3))
                                    if c1:
                                        self.__board.updateenemy1b(
                                            x[count],
                                            enemy1[count, :].decode())
                                        #updating prev array
                                        enemy1[count, 3] = enemy1[count, 1]
                                        enemy1[count,
                                               2] = self.__board.getgrid(
                                                   35, x[count] - 2)
                                        enemy1[count,
                                               1] = self.__board.getgrid(
                                                   35, x[count] - 3)
                                        enemy1[count,
                                               0] = self.__board.getgrid(
                                                   34, x[count] - 2)
                                        x[count] -= 2
                                        self.__board.updateenemy1(34, x[count])
                                else:
                                    c1 = checkmv(
                                        self.__board.getgrid(35, x[count] + 3))
                                    if c1:
                                        self.__board.updateenemy1f(
                                            x[count],
                                            enemy1[count, :].decode())
                                        #updating prev array
                                        enemy1[count,
                                               0] = self.__board.getgrid(
                                                   34, x[count] + 2)
                                        enemy1[count, 1] = enemy1[count, 3]
                                        enemy1[count,
                                               2] = self.__board.getgrid(
                                                   35, x[count] + 2)
                                        enemy1[count,
                                               3] = self.__board.getgrid(
                                                   35, x[count] + 3)
                                        x[count] += 2
                                        self.__board.updateenemy1(34, x[count])
                            time.sleep(0.03)
                            os.system('clear')
                            self.__board.printboard(i, mariopresent[1], life,
                                                    score, bullet)

                    if time.time() - loop2 > check - 0.5:
                        loop2 = time.time()
                        #FOR ENEMY2
                        if len(y) != 0 and i + 100 > y[len(y) - 1] > i:
                            for count in range(len(y)):
                                c1 = checkmv(
                                    self.__board.getgrid(35, y[count] - 2))
                                if c1:
                                    self.__board.updateenemy2b(
                                        y[count], enemy2[count, :].decode())

                                    #updating prev array
                                    enemy2[count, 4] = enemy2[count, 2]
                                    enemy2[count, 3] = self.__board.getgrid(
                                        35, y[count])
                                    enemy2[count, 2] = self.__board.getgrid(
                                        35, y[count] - 1)
                                    enemy2[count, 1] = self.__board.getgrid(
                                        34, y[count] - 1)
                                    enemy2[count, 0] = self.__board.getgrid(
                                        34, y[count] - 2)
                                    y[count] -= 2
                                    self.__board.updateenemy2(34, y[count])
                            #faster
                            time.sleep(0.01)
                            os.system('clear')
                            self.__board.printboard(i, mariopresent[1], life,
                                                    score, bullet)

                    #dead if in contact with enemy
                    if marioprev[6] == "x" or marioprev[
                            7] == "x" or self.__board.getgrid(
                                mariopresent[0] + 1, mariopresent[1]) == "Q":
                        #not updating enemy prev so it shows dead location
                        life -= 1
                        os.system('aplay ./sounds/smb_mariodie.wav')
                        screen.reset(self)

                    #if all lives used up
                    if life <= 0:
                        os.system('clear')
                        os.system('aplay ./sounds/smb_gameover.wav')
                        print("GAME OVER   ALL LIVES USED")
                        break

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

        finally:
            termios.tcsetattr(sys.stdin, termios.TCSADRAIN, old_settings)
Example #55
0
    def take_control(self):
        """
        This function is a better documented and touched up version of the
        posix_shell function found in the interactive.py demo script that
        ships with Paramiko.
        """

        if has_termios:
            # Get attributes of the shell you were in before going to the
            # new one
            original_tty = termios.tcgetattr(sys.stdin)
            try:
                tty.setraw(sys.stdin.fileno())
                tty.setcbreak(sys.stdin.fileno())

                # We must set the timeout to 0 so that we can bypass times when
                # there is no available text to receive
                self.channel.settimeout(0)

                # Loop forever until the user exits (i.e. read buffer is empty)
                while True:
                    select_read, select_write, select_exception = (
                        select.select([self.channel, sys.stdin], [], []))
                    # Read any output from the terminal and print it to the
                    # screen.  With timeout set to 0, we just can ignore times
                    # when there's nothing to receive.
                    if self.channel in select_read:
                        try:
                            buffer = self.channel.recv(self.buffer_size)
                            if len(buffer) == 0:
                                break
                            sys.stdout.write(buffer.decode(self.encoding))
                            sys.stdout.flush()
                        except socket.timeout:
                            pass
                    # Send any keyboard input to the terminal one byte at a
                    # time
                    if sys.stdin in select_read:
                        buffer = sys.stdin.read(1)
                        if len(buffer) == 0:
                            break
                        self.channel.send(buffer)
            finally:
                # Restore the attributes of the shell you were in
                termios.tcsetattr(sys.stdin, termios.TCSADRAIN, original_tty)
        else:

            def writeall(sock):
                while True:
                    buffer = sock.recv(self.buffer_size)
                    if len(buffer) == 0:
                        break
                    sys.stdout.write(buffer.decode(self.encoding))
                    sys.stdout.flush()

            writer = threading.Thread(target=writeall, args=(self.channel, ))
            writer.start()

            try:
                while True:
                    buffer = sys.stdin.read(1)
                    if len(buffer) == 0:
                        break
                    self.channel.send(buffer)
            # User has hit Ctrl+Z or F6
            except EOFError:
                pass
Example #56
0
def streamSwingTrial():
    """Runs a swing trial event and computes important bat metrics
    Returns the bat metrics in an array
    """

    imu = initialize()
    print "5 seconds to Calibrate. Please hold Calibration Position:"
    tm.sleep(5.5)  # Wait for calibration position
    e_initial = calibrate(imu)  # Obtain four initial euler parameters
    #e_initial = normalizeEulerParameters(e_initial) #Normalize

    initialTime = tm.time()  # Time

    # Initialize Storage Vectors
    acceleration = readAcceleration(imu)
    angularVelocity = readAngularVelocity(imu)
    try:
        tty.setcbreak(sys.stdin.fileno())
        # Loop for 10 seconds
        input(
            'press 1 to stop program\n press 2 to kill recording\n press 3 to start recording \n press 4 to record at 10 deg'
        )
        isSwinging = False
        while (keyboard() != 'stop'):
            xinertialAccelerationVector = [0]
            yinertialAccelerationVector = [0]
            zinertialAccelerationVector = [0]
            velocityMagnitudeVector = [0]
            xAccelerationVector = [acceleration[0]]
            yAccelerationVector = [acceleration[1]]
            zAccelerationVector = [acceleration[2]]
            xAngularVelocity = [angularVelocity[0]]
            yAngularVelocity = [angularVelocity[1]]
            zAngularVelocity = [angularVelocity[2]]
            aimAngleVector = [0]
            rollVector = [0]
            rotationMatrices = [computeDirectionCosineMatrix(e_initial)]
            elevationAngles = [0]
            timeVectors = [0]
            sampleTimes = [0]
            calibration_angles = [0]

            # Initialize useful computation variables
            previousEpochTime = initialTime  # t0
            previousElapsedSampleTime = 0
            currentElapsedSampleTime = 0
            previousEulerParameters = e_initial
            index = 0
            while (keyboard() != 'kill'):
                #read callibration angles
                tm.sleep(.5)
                if ((keyboard() != 'kill') and (keyboard() != 'stop')):
                    calibration_angles.append(keyboard())

                    # Read Angular Velocity and Acceleration
                    currentAngularVelocity = readAngularVelocity(imu)
                    currentAcceleration = readAcceleration(imu)
                    xAccelerationVector.append(currentAcceleration[0])
                    yAccelerationVector.append(currentAcceleration[1])
                    zAccelerationVector.append(currentAcceleration[2])
                    xAngularVelocity.append(currentAngularVelocity[0])
                    yAngularVelocity.append(currentAngularVelocity[1])
                    zAngularVelocity.append(currentAngularVelocity[2])

                    currentEpochTime = tm.time()
                    currentElapsedSampleTime = currentEpochTime - previousEpochTime
                    sampleTimes.append(currentElapsedSampleTime)
                    timeVectors.append(
                        previousElapsedSampleTime + currentElapsedSampleTime
                    )  # Time History TODO: CHANGE NAME TO AVOID CONFUSION
                    timeVector = [0, currentElapsedSampleTime]

                    # TODO:Do we have to normalize the quaternion?
                    # TODO:Can we use this same solver or do we have to switch

                    # Solve for current rotation matrix
                    currentEulerParameters = computeEulerParameters(
                        previousEulerParameters, timeVector,
                        currentAngularVelocity)
                    eulerParametersNormalized = currentEulerParameters
                    #eulerPrametersNoramlized = normalizeEulerParameters(currentEulerParameters)

                    # Compute Direction Cosine Matrix
                    directionMatrix = computeDirectionCosineMatrix(
                        eulerParametersNormalized)
                    rotationMatrices.append(directionMatrix)

                    #print "Direction Cosine Matrix:", directionMatrix[0]

                    # Get Inertial Acceleration snd Velocity
                    xinertialAcceleration, yinertialAcceleration, zinertialAcceleration = computeInertialAcceleration(
                        imu, directionMatrix)
                    xinertialAccelerationVector.append(xinertialAcceleration)
                    yinertialAccelerationVector.append(yinertialAcceleration)
                    zinertialAccelerationVector.append(zinertialAcceleration)

                    # Stop collecting data once acceleration has reached zero again.
                    previousEulerParameters = currentEulerParameters
                    previousEpochTime = currentEpochTime
                    previousElapsedSampleTime += currentElapsedSampleTime  # move to next step

                    #Calculate Yaw, pitch and roll
                    elevationAngle = asin(directionMatrix[0][2]) * 57.3
                    aimAngle = atan(
                        directionMatrix[0][1] / directionMatrix[0][0]) * 57.3
                    #roll = currentEulerParameters[3]**2 - currentEulerParameters[1]**2 \
                    #       - currentEulerParameters[2]**2 - currentEulerParameters[3]**2

                    #roll = acos(roll) * 57.3

                    roll = atan(
                        directionMatrix[1][2] / directionMatrix[2][2]) * 57.3

                    elevationAngles.append(elevationAngle)
                    aimAngleVector.append(aimAngle)
                    rollVector.append(roll)
                    isSwinging = True

                # Compute Velocity
            if (isSwinging):
                xinertialVelocity = computeVelocity(
                    xinertialAccelerationVector, sampleTimes)
                yinertialVelocity = computeVelocity(
                    yinertialAccelerationVector, sampleTimes)
                zinertialVelocity = computeVelocity(
                    zinertialAccelerationVector, sampleTimes)

                xpositionVector = computePosition(xinertialVelocity,
                                                  sampleTimes)
                ypositionVector = computePosition(yinertialVelocity,
                                                  sampleTimes)
                zpositionVector = computePosition(zinertialVelocity,
                                                  sampleTimes)

                #TODO: FIX THIS
                velocityMagnitude = computeVelocityMagnitude(
                    xinertialVelocity, yinertialVelocity, zinertialVelocity)
                velocityMagnitudeVector.append(velocityMagnitude)
                sweetSpotVelocityVector = computeSweetSpotVelocity(
                    [xinertialVelocity, yinertialVelocity, zinertialVelocity],
                    [xAngularVelocity, yAngularVelocity, zAngularVelocity])

                roundEntries(xAccelerationVector)
                roundEntries(yAccelerationVector)
                roundEntries(zAccelerationVector)
                roundEntries(xAngularVelocity)
                roundEntries(yAngularVelocity)
                roundEntries(zAngularVelocity)
                roundEntries(elevationAngles)
                roundEntries(timeVectors)
                roundEntries(xinertialVelocity)
                roundEntries(yinertialVelocity)
                roundEntries(zinertialVelocity)
                roundEntries(xinertialAccelerationVector)
                roundEntries(yinertialAccelerationVector)
                roundEntries(zinertialAccelerationVector)
                roundEntries(aimAngleVector)
                roundEntries(rollVector)
                roundEntries(sweetSpotVelocityVector)
                roundEntries(velocityMagnitude)
                roundEntries(xpositionVector)
                roundEntries(ypositionVector)
                roundEntries(zpositionVector)

                max_acceleration_x = maxValue(xinertialAccelerationVector)
                max_acceleration_y = maxValue(yinertialAccelerationVector)
                max_acceleration_z = maxValue(zinertialAccelerationVector)
                Magnitude = magnitude(max_acceleration_x, max_acceleration_y,
                                      max_acceleration_z)
                list_magnitude = listMagnitude(xinertialAccelerationVector,
                                               yinertialAccelerationVector,
                                               zinertialAccelerationVector)
                good_swing = input("\n Enter 1 for good and zero for bad \n")
                payload = {
                    "firstname": firstname,
                    "swing_speed_mag": Magnitude,
                    "swing_speed": list_magnitude,
                    "good_swing": good_swing
                }

                r = requests.post(
                    'https://baseballperformance.herokuapp.com/contacts',
                    json=payload)
                isSwinging = False
        # s.connect(('192.168.1.41', port))
        # transmitString = listToString(xAccelerationVector)
        # transmitString = transmitString + '!'
        # transmitString = transmitString + listToString(yAccelerationVector)
        # transmitString = transmitString + '!'
        # transmitString = transmitString + listToString(zAccelerationVector)
        # transmitString = transmitString + '!'
        # transmitString = transmitString + listToString(xAngularVelocity)
        # transmitString = transmitString + '!'
        # transmitString = transmitString + listToString(yAngularVelocity)
        # transmitString = transmitString + '!'
        # transmitString = transmitString + listToString(zAngularVelocity)
        # transmitString = transmitString + '!'
        # transmitString = transmitString + listToString(elevationAngles)
        # transmitString = transmitString + '!'
        # transmitString = transmitString + listToString(timeVectors)
        # transmitString = transmitString + '!'
        # transmitString = transmitString + listToString(xinertialVelocity)
        # transmitString = transmitString + '!'
        # transmitString = transmitString + listToString(yinertialVelocity)
        # transmitString = transmitString + '!'
        # transmitString = transmitString + listToString(zinertialVelocity)
        # transmitString = transmitString + '!'
        # transmitString = transmitString + listToString(xinertialAccelerationVector)
        # transmitString = transmitString + '!'
        # transmitString = transmitString + listToString(yinertialAccelerationVector)
        # transmitString = transmitString + '!'
        # transmitString = transmitString + listToString(zinertialAccelerationVector)
        # transmitString = transmitString + '!'
        # transmitString = transmitString + listToString(aimAngleVector)
        # transmitString = transmitString + '!'
        # transmitString = transmitString + listToString(rollVector)
        # transmitString = transmitString + '!'
        # transmitString = transmitString + listToString(sweetSpotVelocityVector)
        # transmitString = transmitString + '!'
        # transmitString = transmitString + listToString(velocityMagnitude)
        # transmitString = transmitString + '!'
        # transmitString = transmitString + listToString(xpositionVector)
        # transmitString = transmitString + '!'
        # transmitString = transmitString + listToString(ypositionVector)
        # transmitString = transmitString + '!'
        # transmitString = transmitString + listToString(zpositionVector)
        # transmitString = transmitString + '!'
        # transmitString = transmitString + listToString(calibration_angles)
        #
        # sendData(transmitString)
        s.close()

    finally:
        termios.tcsetattr(sys.stdin, termios.TCSADRAIN, old_settings)
Example #57
0
def interactive(channel, command):
    # 获取原tty属性
    oldtty = termios.tcgetattr(sys.stdin)

    try:
        # 设置 tty 的属性
        tty.setraw(sys.stdin.fileno())
        tty.setcbreak(sys.stdin.fileno())
        channel.settimeout(1.5)

        # ssh连接进入主机后 执行命令 比如: 要进入docker 容器
        if command != "":
            channel.send(command + "\r")

        # 获取终端大小
        term_size = os.get_terminal_size()
        w_old = term_size.columns
        h_old = term_size.lines

        tm = 2
        input_cmd = ""
        input_string = "\r"
        note = input_handle.InputHandle()
        left_arrow_count = 0
        right_arrow_count = 0
        while True:
            # 获取终端大小
            term_size = os.get_terminal_size()
            w = term_size.columns
            h = term_size.lines
            # 如果窗口大小变了,更更改
            if w != w_old or h != h_old:
                w_old = w
                h_old = h
                # 重置 虚拟终端的大小
                channel.resize_pty(w, h)
                continue
            # 更改 channel 会发生 InterruptedError 异常。
            try:
                rlist, wlist, errlist = select.select([channel, sys.stdin], [],
                                                      [])
            except InterruptedError:
                continue

            # (logger, fh) = logs.log(log_file=configs.CONFIG['logfile_debug'], log_fmode="a")
            # logger.debug("{channel len: %s}" % dir(channel.in_buffer._buffer))
            # logger.debug("{dir(channel.recv): %s}" % help(channel.recv))
            # logger.debug("{channel : %s}" % channel.in_buffer._buffer)
            # logger.debug("{channel len: %s}" % len(channel.in_buffer._buffer))
            # logger.removeHandler(fh)

            # 从标准输入和socket 获取数据然后写入标准输出
            if channel in rlist:
                try:
                    # 启动交互 头两次等待一小会儿,然数据接受完整(为了登录时不显示 docker exec -it 进入容器这一步)
                    if tm > 0:
                        time.sleep(0.2 * tm)
                        tm = tm - 1
                    # 接收多少个字节
                    r = channel.recv(1024)

                    # tab 补全
                    if input_string == '\t' and r[:2] != b"\r\n" and r[:1] != b"\x07" and r[
                            -23:] != b"possibilities? (y or n)":
                        input_cmd = input_cmd + output.u_reconsitution(r)

                        # (logger, fh) = logs.log(log_file=configs.CONFIG['logfile_debug'], log_fmode="a")
                        # logger.debug("{input_string: %s r[:1]: %s }" % ([input_string], r[:1]))
                        # logger.debug("{input_cmd: %s r[:3]: %s }" % ([input_cmd], r[:3]))
                        # logger.removeHandler(fh)

                    # (logger, fh) = logs.log(log_file=configs.CONFIG['logfile_debug'], log_fmode="a")
                    # logger.debug("{1 note.yn: %s}" % note.yn)
                    recv_list = r.split(b'\r\n')
                    # logger.debug("{rlist : %s}" % recv_list)
                    # logger.debug("{r length : %s}" % len(r))
                    # logger.debug("{rlist[-1] : %s}" % rlist[-1])

                    # 更改 补全提示状态
                    if recv_list[-1] != b"--More--" and len(r) < 1024:
                        note.yn = False
                    elif recv_list[-1] == b"--More--":
                        note.yn = True
                    # logger.debug("{6 note.yn : %s}" % note.yn)
                    # logger.removeHandler(fh)

                    if input_string == "\t" and r[
                            -23:] == b"possibilities? (y or n)":
                        note.yn = True

                    # (logger, fh) = logs.log(log_file=configs.CONFIG['logfile_debug'], log_fmode="a")
                    # logger.debug("{2 note.yn: %s}" % note.yn)
                    # logger.removeHandler(fh)

                    status = output.output(r)
                    if status == "exit":
                        break
                    elif status == None:
                        pass
                except socket.timeout:
                    pass
            # 从标准输入获取输入的字符:然后,处理输入,对输入进行过滤
            if sys.stdin in rlist:
                input_string = funkey(stdinput=sys.stdin)
                if input_string == "break":
                    break
                # elif input_string == "left_arrow\x1b[D":
                #     left_arrow_count = left_arrow_count + 1
                #     input_string = '\x1b[D'
                # elif input_string == "right_arrow\x1b[C":
                #     right_arrow_count = right_arrow_count + 1
                #     input_string = '\x1b[C'
                #
                # if len(input_cmd) == 0:
                #     pass
                # else:
                #     cursor_position = left_arrow_count - right_arrow_count
                #     if cursor_position <= 0:
                #         cursor_position = 0
                #     elif cursor_position >= len(input_cmd):
                #         cursor_position = len(input_cmd)
                #
                #     if input_string == "\x08" and cursor_position < len(input_cmd):
                #         input_cmd = input_cmd[:-(cursor_position + 1)] + input_cmd[-cursor_position:]

                # 命令过滤
                input_string, input_cmd = filter.filter_stdin(
                    input_string=input_string, input_cmd=input_cmd, yesno=note)
                # 把输入的字符发送给 远程ssh (准确的说是:经过过滤过的输入)
                channel.send(input_string)
    except Exception as e:
        fe = traceback.format_exc()
        (logger, fh) = logs.log(log_file=configs.CONFIG['logfile_error'],
                                log_fmode="a")
        logger.error("{ error }:%s \n %s" % (e, fe))
        logger.removeHandler(fh)
    finally:
        termios.tcsetattr(sys.stdin, termios.TCSADRAIN, oldtty)
Example #58
0
def oauth_ssh():
    account, port, acct_fqdn, command = parse_args()

    fqdn = acct_fqdn.split('@')[-1]

    # Grab the access token
    access_token = find_access_token(fqdn)

    # Explicit account settings : Set on command line
    if len(acct_fqdn.split('@')) > 1:
        account = acct_fqdn.split('@')[0]

    # Implicit account settings: Use the account map
    if account is None:
        acct_map = Config.load_object(fqdn, AccountMap)
        if acct_map is None:
            acct_map = SSHService(fqdn, port).get_account_map(access_token)
            Config.save_object(fqdn, acct_map)
        if acct_map['permitted_accounts'] is not None:
            if getpass.getuser() in acct_map['permitted_accounts']:
                account = getpass.getuser()
            elif len(acct_map['permitted_accounts']) == 1:
                account = acct_map['permitted_accounts'][0]

    if account is None:
        print(
            'Could not determine remote account to use. Please use -l <account>.'
        )
        sys.exit(1)

    try:
        transport = SSHService(fqdn, port).login(access_token, account)
    except:
        raise

    channel = transport.open_session()
    channel.setblocking(0)

    if command is not None and len(command) > 0:
        channel.exec_command(' '.join(command))
    else:
        channel.get_pty()
        channel.invoke_shell()

    try:
        oldtty = None
        if os.isatty(sys.stdin.fileno()):
            # Enable one char at a time, don't wait on lines, but do interpret
            # escape characters
            oldtty = termios.tcgetattr(sys.stdin)
            tty.setcbreak(sys.stdin.fileno())
            if command is None or len(command) == 0:
                # Forward escapes like control-C
                tty.setraw(sys.stdin.fileno())
        channel.settimeout(None)

        watch_list = [channel, sys.stdin]
        while True:
            r, w, e = select.select(watch_list, [], [])
            if channel in r:
                try:
                    x = channel.recv(1024).decode(sys.stdout.encoding)
                    if len(x) == 0:
                        break
                    sys.stdout.write(x)
                    sys.stdout.flush()
                except socket.timeout:
                    pass

            if sys.stdin in r:
                x = sys.stdin.read(1)
                if len(x) == 0:
                    watch_list.remove(sys.stdin)
                else:
                    channel.send(x)
    finally:
        if oldtty is not None:
            termios.tcsetattr(sys.stdin, termios.TCSADRAIN, oldtty)

    sys.exit(channel.recv_exit_status())
Example #59
0
def set_cbreak(fd):
    tty.setcbreak(fd)
Example #60
0
    def cbreak_input_mode():
        """Set the terminal input mode to cbreak
        """
        tty.setcbreak(sys.stdin.fileno())

        pass