예제 #1
0
    def missing_host_key(self, client, hostname, key):

        if C.HOST_KEY_CHECKING:

            fcntl.lockf(self.runner.process_lockfile, fcntl.LOCK_EX)
            fcntl.lockf(self.runner.output_lockfile, fcntl.LOCK_EX)

            old_stdin = sys.stdin
            sys.stdin = self.runner._new_stdin
            fingerprint = hexlify(key.get_fingerprint())
            ktype = key.get_name()
            
            # clear out any premature input on sys.stdin
            tcflush(sys.stdin, TCIFLUSH)

            inp = raw_input(AUTHENTICITY_MSG % (hostname, ktype, fingerprint))
            sys.stdin = old_stdin
            if inp not in ['yes','y','']:
                fcntl.flock(self.runner.output_lockfile, fcntl.LOCK_UN)
                fcntl.flock(self.runner.process_lockfile, fcntl.LOCK_UN)
                raise errors.AnsibleError("host connection rejected by user")

            fcntl.lockf(self.runner.output_lockfile, fcntl.LOCK_UN)
            fcntl.lockf(self.runner.process_lockfile, fcntl.LOCK_UN)


        key._added_by_ansible_this_time = True

        # existing implementation below:
        client._host_keys.add(hostname, key.get_name(), key)
예제 #2
0
    def read(self):
    ##  Recoge los datos de consumo leyendo el puerto correpondiente
    ##  Lee del dispositivo de medida wattsup

        fd = open(self.url, "a+", 1)
        [iflag, oflag, cflag, lflag, ispeed, ospeed, cc] = termios.tcgetattr(fd)
        tty.setraw(fd)
        termios.tcflush(fd, termios.TCIFLUSH)
        termios.tcsetattr(fd, termios.TCSANOW, [iflag | termios.IGNPAR, oflag, cflag & ~termios.CSTOPB, lflag, termios.B115200, termios.B115200, cc])

        # logging.debug("Dispositivo %s abierto", self.url)
        fd.write("#L,R,0;")
        # logging.debug("Enviado 'stop' a %s", self.url)
        fd.write("#R,W,0;")
        # logging.debug("Enviado 'reset' a %s", self.url)
        fd.write("#L,W,3,E,1,1;")
        # logging.debug("Enviado 'start' a %s", self.url)
        fd.flush()

        power       = [0] * len(self.lines)
        sample      = ["0"] * len(self.lines)

        while self.running:
            select.select([fd], [], [])
            sample= fd.readline().strip(" \n\t\r;").split(',')[3:]
            if len(sample) == 18:
                power[0] = float(sample[0]) * 1e-1
  	        yield power
예제 #3
0
    def missing_host_key(self, client, hostname, key):

        if all((C.HOST_KEY_CHECKING, not C.PARAMIKO_HOST_KEY_AUTO_ADD)):

            if C.USE_PERSISTENT_CONNECTIONS:
                raise AnsibleConnectionFailure('rejected %s host key for host %s: %s' % (key.get_name(), hostname, hexlify(key.get_fingerprint())))

            self.connection.connection_lock()

            old_stdin = sys.stdin
            sys.stdin = self._new_stdin

            # clear out any premature input on sys.stdin
            tcflush(sys.stdin, TCIFLUSH)

            fingerprint = hexlify(key.get_fingerprint())
            ktype = key.get_name()

            inp = input(AUTHENTICITY_MSG % (hostname, ktype, fingerprint))
            sys.stdin = old_stdin

            self.connection.connection_unlock()

            if inp not in ['yes', 'y', '']:
                raise AnsibleError("host connection rejected by user")

        key._added_by_ansible_this_time = True

        # existing implementation below:
        client._host_keys.add(hostname, key.get_name(), key)
예제 #4
0
    def missing_host_key(self, client, hostname, key):

        if C.HOST_KEY_CHECKING:

            self.connection.connection_lock()

            old_stdin = sys.stdin
            sys.stdin = self._new_stdin

            # clear out any premature input on sys.stdin
            tcflush(sys.stdin, TCIFLUSH)

            fingerprint = hexlify(key.get_fingerprint())
            ktype = key.get_name()

            inp = raw_input(AUTHENTICITY_MSG % (hostname, ktype, fingerprint))
            sys.stdin = old_stdin

            self.connection.connection_unlock()

            if inp not in ['yes','y','']:
                raise AnsibleError("host connection rejected by user")

        key._added_by_ansible_this_time = True

        # existing implementation below:
        client._host_keys.add(hostname, key.get_name(), key)
예제 #5
0
파일: reg.py 프로젝트: JuniorMario/Barionix
def findTags(string):
	termios.tcflush(sys.stdin,termios.TCIFLUSH)
	sys.stdout.flush()
	global tags
	global preTags
	if '<' in string:
		string = string.split('<')
		for stri in string:
			if '>' in stri:
				preTags.append(stri)
			else:
				pass
		for tag in preTags:
			if '>' in tag and tag.endswith('>'):
				tags.append(tag)
			elif '>' in tag and tag.endswith('>') == False:
				tag = tag.split('>')
				tags.append(tag[0])
			else:
				pass
		termios.tcflush(sys.stdin,termios.TCIFLUSH)
		sys.stdout.flush()
		return tags
	else:
		return False
예제 #6
0
 def flushOutput(self):
     """\
     Clear output buffer, aborting the current output and discarding all
     that is in the buffer.
     """
     if not self._isOpen: raise portNotOpenError
     termios.tcflush(self.fd, TERMIOS.TCOFLUSH)
예제 #7
0
    def Connect(self):

        self.file = open_rfcomm(self.port, os.O_RDWR)

        tty.setraw(self.file)

        attrs = termios.tcgetattr(self.file)

        attrs[0] &= ~(termios.IGNCR | termios.ICRNL | termios.IUCLC | termios.INPCK | termios.IXON | termios.IXANY |
                      termios.IGNPAR)
        attrs[1] &= ~(termios.OPOST | termios.OLCUC | termios.OCRNL | termios.ONLCR | termios.ONLRET)
        attrs[3] &= ~(termios.ICANON | getattr(termios, 'XCASE', 4) | termios.ECHO | termios.ECHOE | termios.ECHONL)
        attrs[3] &= ~(termios.ECHO | termios.ECHOE)
        attrs[6][termios.VMIN] = 1
        attrs[6][termios.VTIME] = 0
        attrs[6][termios.VEOF] = 1

        attrs[2] &= ~(termios.CBAUD | termios.CSIZE | termios.CSTOPB | termios.CLOCAL | termios.PARENB)
        attrs[2] |= (termios.B9600 | termios.CS8 | termios.CREAD | termios.PARENB)

        termios.tcsetattr(self.file, termios.TCSANOW, attrs)

        termios.tcflush(self.file, termios.TCIOFLUSH)

        self.send_commands()
예제 #8
0
파일: util.py 프로젝트: davidhodo/bloom
def flush_stdin():
    try:
        from termios import tcflush, TCIOFLUSH
        tcflush(sys.stdin, TCIOFLUSH)
    except ImportError:
        # fallback if not supported on some platforms
        pass
예제 #9
0
파일: rgm3800.py 프로젝트: snaewe/rgm3800py
  def __init__(self, filename):
    """Initialize serial communication object.

    Args:
      filename:  String, name of serial device, e.g. '/dev/ttyS0'.
    """
    self.__receiver_running = False

    # Open device and set serial communications parameters.
    # (115k baud, 8N1, no handshake, no buffering in kernel)
    self._fd = os.open(filename, os.O_RDWR | os.O_NOCTTY | os.O_NONBLOCK)
    attr = termios.tcgetattr(self._fd)
    attr[0] = 0   # iflag
    attr[1] = 0   # oflag
    attr[2] = termios.CS8 | termios.CREAD | termios.CLOCAL  # cflag
    attr[3] = 0   # lflag
    attr[4] = termios.B115200  # ispeed
    attr[5] = termios.B115200  # ospeed
    attr[6][termios.VMIN] = 1
    attr[6][termios.VTIME] = 0
    termios.tcsetattr(self._fd, termios.TCSAFLUSH, attr)

    # Clean kernel buffers of stale data.
    termios.tcflush(self._fd, termios.TCIOFLUSH)

    # Set up communication buffers and start receiver thread.
    self.__buffer = Queue.Queue(0)
    self.__buffer2 = None

    self.__receiver = threading.Thread(target=self.__ReceiverThread)
    self.__receiver_running = True
    self.__receiver.start()
예제 #10
0
def move_turret(x):
    if DEVICE:
        if x == 'w':
            send_cmd(UP)
        if x == 'a':
            send_cmd(LEFT)
        if x == 's':
            send_cmd(DOWN)
        if x == 'd':
            send_cmd(RIGHT)
        if x == ' ':
            send_cmd(STOP)
        if x == 'f':
            send_cmd(FIRE)
            time.sleep(5)
            termios.tcflush(sys.stdin, termios.TCIOFLUSH)
        if x == 'r':
            send_cmd(LEFT)
            time.sleep(6)
            send_cmd(DOWN)
            time.sleep(1)
            send_cmd(RIGHT)
            time.sleep(3)
            send_cmd(UP)
            time.sleep(.5)
            send_cmd(STOP)
예제 #11
0
def getVal(desc, default):
	# discard any previos input (prevent old input from answering the question)
	termios.tcflush(sys.stdin, termios.TCIOFLUSH)
	value = raw_input("%s [%s]:"%(desc, default))
	if value.strip() == "":
		return default
	return value
예제 #12
0
	def startIO(self):
		fdin = sys.stdin.fileno()
		fdout = sys.stdout.fileno()
		termios.tcflow(fdin, termios.TCION)
		termios.tcflush(fdin, termios.TCIFLUSH)
		termios.tcflush(fdout, termios.TCOFLUSH)
		termios.tcflow(fdout, termios.TCOON)
예제 #13
0
def listen():
	while 1:
		x = getch()
		if x == 'w':
			send_cmd(UP)
		if x == 'a':
			send_cmd(LEFT)	
		if x == 's':
			send_cmd(DOWN)
		if x == 'd':
			send_cmd(RIGHT)
		if x == ' ':
			send_cmd(STOP)
		if x == 'f':
			send_cmd(FIRE)
			play_sound(dalekGun)
			time.sleep(5)
			termios.tcflush(sys.stdin, termios.TCIOFLUSH)
		if x == 'r':
			send_cmd(LEFT)
			time.sleep(6)
			send_cmd(DOWN)
			time.sleep(1)
			send_cmd(RIGHT)
			time.sleep(3)
			send_cmd(UP)
			time.sleep(.5)
			send_cmd(STOP)
			termios.tcflush(sys.stdin, termios.TCIOFLUSH)
		if x == 'k':
			print""
			print "SHUT DOWN SEQUENCE INITIATED"
			break
예제 #14
0
 def flushInput(self):
     """Clear input buffer, discarding all that is in the buffer."""
     if not self._isOpen: raise portNotOpenError
     try:
         termios.tcflush(self.fd, TERMIOS.TCIFLUSH)
     except termios.error as err:
         raise SerialException("flushInput failed: %s" % err)
예제 #15
0
def flushInput():
    try:
        import msvcrt
        while msvcrt.kbhit(): msvcrt.getch()
    except ImportError:
        import sys, termios
        termios.tcflush(sys.stdin, termios.TCIOFLUSH)
예제 #16
0
def test_toggle():
    """Test for all the LEDs on LED8.
    
    Instantiates 8 LED objects and toggles them. This test can be skipped.
    
    """
    global leds
    
    for led in leds:
        led.off()
    leds[0].on()
    leds[2].on()
    leds[4].on()
    leds[6].on()
    
    print("\nToggling Pmod LEDs. Press enter to stop toggling...", end="")
    while True:
        for led in leds:
            led.toggle()
        sleep(0.2)
        if sys.stdin in select.select([sys.stdin], [], [], 0)[0]:
            termios.tcflush(sys.stdin, termios.TCIOFLUSH)
            break
            
    for led in leds:
        led.off()
        
    assert user_answer_yes("Pmod LEDs were toggling?")
    
    del leds
    
    def pose_query(self, question, time_limit):
        self.time_left = time_limit
        self.template = "\r" + question + "(%d s remaining):"
        self._update()
        self.template = "\033[s" + self.template + "\033[u"

        ret = None
        tl = None

        try:
            resp = self.epoll.poll(time_limit) #This checks to see if there is activity on the file descriptor we registered above (stdin)
            
            # Don't worry too much about what epoll.poll returns, 
            # just know that in this case if it returns a tuple of length > 0 that means the user typed something AND pressed enter
            if len(resp) == 0:
                sys.stdout.write("\n")
                print 'Your time is out.'
                user_input = ''
                tl = 0
            else:
                user_input = raw_input() #Read what the user typed from stdin this will have the trailing newline
                try:
                    ret = int(user_input.strip())
                    tl = self.time_left
                except:
                    ret = user_input
        except:
            pass

        self.timer.cancel()
        termios.tcflush(sys.stdin, termios.TCIFLUSH)
        return ret, tl
예제 #18
0
def print_after_score(winner_for_round):
  if winner_for_round == 1 or winner_for_round == 2:
    game_message = "|                       Player " + str(winner_for_round) + " Scores!                      |"
  elif winner_for_round == 0:
    game_message = "|                        No more bullets!                     |"
  elif winner_for_round == 3:
    winner_for_game = 0
    if player_one_score > player_two_score: 
      winner_for_game = 1
    elif player_two_score > player_one_score: 
      winner_for_game = 2
    game_message = "|                  Game Over! Player " + str(winner_for_game) + " Wins!               |"
    
  print "        Score:", player_one_score, "            ", game_time_left, "              Score: ", player_two_score
  for x in range(len(playing_field)):
    if x == 2:
      print game_message
    else:
      for y in range(len(playing_field[0])):
        print playing_field[x][y],
      print ""
  print ""

  # 2 second break
  time.sleep(2)

  # ignore all keystrokes in this period
  tcflush(sys.stdin, TCIOFLUSH)
  refresh_playing_field()
예제 #19
0
파일: frotz.py 프로젝트: jamcut/cassie-bot
	def game_restore(self, restore_file):
		self.frotz_stdin.write(b'restore\n')
		if is_read_ready(self.frotz_stdout, self.read_timeout):
			termios.tcflush(self.frotz_stdout, termios.TCIFLUSH)
		self.frotz_stdin.write((restore_file + '\n').encode('utf-8'))
		output = self.read_output()
		return output
예제 #20
0
 def flushOutput(self):
     """Clear output buffer, aborting the current output and
     discarding all that is in the buffer."""
     if not self._isOpen: raise portNotOpenError
     try:
         termios.tcflush(self.fd, TERMIOS.TCOFLUSH)
     except termios.error as err:
         raise SerialException("flushOutput failed: %s" % err)
예제 #21
0
파일: sleep.py 프로젝트: abutcher/Taboot
 def run(self, runner):
     import time
     start = time.time()
     tcflush(sys.stdin, TCIFLUSH)
     raw_input(self._message)
     return TaskResult(self, success=True,
                       output="Paused for %s seconds" %
                       (time.time() - start))
예제 #22
0
파일: input.py 프로젝트: ditojohn/raspi
def set_term_input(enabled):
    if enabled:
        set_term_echo(sys.stdin, True)                   # Turn echo on
        termios.tcflow(sys.stdin, termios.TCION)         # Resume input
        termios.tcflush(sys.stdin, termios.TCIOFLUSH)    # Flush queued data
    else:
        set_term_echo(sys.stdin, False)                  # Turn echo off
        termios.tcflow(sys.stdin, termios.TCIOFF)        # Suspend input
예제 #23
0
 def reset_output_buffer(self):
     """\
     Clear output buffer, aborting the current output and discarding all
     that is in the buffer.
     """
     if not self.is_open:
         raise portNotOpenError
     termios.tcflush(self.fd, termios.TCOFLUSH)
예제 #24
0
def flush_stdin():
    try:
        import termios  # linux
        termios.tcflush(sys.stdin, termios.TCIOFLUSH)
    except ImportError:
        import msvcrt  # windows
        while msvcrt.kbhit():
            msvcrt.getch()
예제 #25
0
파일: rgm3800.py 프로젝트: snaewe/rgm3800py
 def _Close(self):
   """Flush data and close serial port file handle."""
   if self._fd:
     try:
       termios.tcflush(self._fd, termios.TCIOFLUSH)
     except termios.error:
       pass
     os.close(self._fd)
     self._fd = None
예제 #26
0
 def __getKey():
     """Return a key pressed by the user"""
     try:
         tty.setcbreak(sys.stdin.fileno())
         termios.tcflush(sys.stdin, termios.TCIOFLUSH)
         ch = sys.stdin.read(1)
         return ord(ch) if ch else None
     finally:
         termios.tcsetattr(__fd, termios.TCSADRAIN, __old)
def read_line(msg = '', default = ''):
    if not os.isatty(1):
        return default
    termios.tcflush(sys.stdin, termios.TCIFLUSH)
    try:
        return raw_input(msg).strip()
    except KeyboardInterrupt:
        print('')
        sys.exit(1)
예제 #28
0
 def flush(self):
     """
     flush stdin... untested on Windows"
     """
     if os.name == 'nt':
         while self.kbhit():
             self.getch()
     else:
         termios.tcflush(sys.stdin, termios.TCIOFLUSH)
     return
예제 #29
0
def flush_input():
    """ Flushes stdin, platform intependant.
    """
    try:
        import sys, termios
        termios.tcflush(sys.stdin, termios.TCIOFLUSH)
    except ImportError:
        import msvcrt
        while msvcrt.kbhit():
            msvcrt.getch()
예제 #30
0
 def wrappedAsk(self):
     """ Wrapper around ask function. Here we can do things such as input buffer flushing and adding newlines when running in an action """
     if termios:
         if self.state in [self.ConfigMode.ADD, self.ConfigMode.REVIEW, self.ConfigMode.PARTIALADD]:
             termios.tcflush(0, termios.TCIFLUSH)
     j.action.startOutput()
     self.dialogMessage("")
     self.ask()
     self.dialogMessage("")
     j.action.stopOutput()
예제 #31
0
def flush_input(): # only works on LINUX
  termios.tcflush(sys.stdin, termios.TCIOFLUSH)
  stdout.flush()
예제 #32
0
def hut_2(items):
    """Hut2 Zone."""
    # current_location = [2, 5]
    directions = ["s"]
    destinations = [0, hut_1, 0, 0]
    print_pause("\nWitch's Hut Interior\n", 1)
    print_pause("You are in the witch's hut\n", 2)
    if 'Stinky Mushroom' not in items:
        if 'Gloves' not in items:
            termios.tcflush(sys.stdin, termios.TCIOFLUSH)
            os.system("stty echo")
            print_pause(
                "   'Well you're a new face! Do you think"
                " you could help a little old lady?'", 2)
            choice = valid_input("\nY/N\n", ["y", "n"])
            if choice == "n":
                os.system("stty -echo")
                print_pause("'Well then get the hell out of my hut!'", 2)
                print_pause(
                    "She teleports you away,"
                    " leaving your items behind.", 3)
                items.clear()
                cave_2(items)
            elif choice == "y":
                os.system("stty -echo")
                print_pause("\n   'Oh Goody!'\n", 2)
                print_pause(
                    "   'There is a mushroom in a "
                    "cave past the swamp to\n"
                    "    the east that I need to "
                    "craft a special potion.'\n", 3)
                print_pause(
                    "   'I would go myself but"
                    " the place smells like hell,\n "
                    "   its pitch black in there,"
                    " and there's a nasty "
                    "troll\n    who has moved in!'\n", 3.5)
                print_pause(
                    "   'If you help me get it I "
                    "can magic you home!'\n\n", 4)
                print_pause(
                    "   'By the way, mushroom is "
                    "poisonus to the touch, \n"
                    "    take these gloves with you!'", 2)
                items.append('Gloves')
                print_pause("\n\nYou acquired 'Gloves'\n", 2)
                hut_2(items)
        elif 'Troll Tooth' not in items:
            print_pause("Granny Weatherwax says,\n\n   'By the way...'\n\n", 3)

            if 'Bandana' not in items:
                print_pause(
                    "   'You'll need something to help"
                    " you breathe in the swamp'\n", 2)
            else:
                print_pause(
                    "   'That Bandana should help you"
                    " get through the stench in the swamp'\n", 2)
            if 'Torch' not in items:
                print_pause(
                    "   'You'll need some way to see"
                    " in the cave, it is very dark'\n", 2)
            else:
                print_pause(
                    "   'That torch should help"
                    " you see in the cave.'\n", 2)
            if 'Sword' not in items:
                print_pause(
                    "   'You'll need some way to fight that troll. "
                    "They can be very dangerous'\n", 2)
                if 'Torch' not in items:
                    print_pause(
                        "   'I've also heard that"
                        " trolls don't like fire'\n", 2)
            else:
                print_pause(
                    "   'I hope you know how to use that sword,"
                    " you'll need it to defeat the troll!'\n", 2)
        else:
            print_pause("   'Oh goody, you got rid of that nasty troll'", 2)
        choose_direction(directions, destinations, items)
    else:
        print_pause("   'Oh goody! My mushroom!!'", 2)
        print_pause("   'Thank you so much!!'\n\n", 8)
        print_pause("\n\n   'Oh you're still here? Off you go!'", 3)
        print_pause("\nYou made it home! Congratulations!\n\n", 2)
        replay()

    choose_direction(directions, destinations, items)
예제 #33
0
def rawInput(string):
    """Flush stdin and then prompt the user for something"""
    if os.name == "posix":
        tcflush(sys.stdin, TCIOFLUSH)
    return input(string)
예제 #34
0
 def flush(self):
     termios.tcflush(self.fileDescriptor, termios.TCIFLUSH)
예제 #35
0
 def read(self):
     "Discard control strings written by gpsd."
     # A tcflush implementation works on Linux but fails on OpenBSD 4.
     termios.tcflush(self.fd, termios.TCIFLUSH)
예제 #36
0
 def runs_tcall():
     termios.tcsendbreak(2, 0)
     termios.tcdrain(2)
     termios.tcflush(2, termios.TCIOFLUSH)
     termios.tcflow(2, termios.TCOON)
예제 #37
0
from pynput.keyboard import Key, Listener
from termios import tcflush, TCIFLUSH
from sys import stdin, stdout

def on_press(key):
    try:
        print key.char.encode("ascii"),
    except AttributeError:
        print str(key)

def on_release(key):
    if(key == Key.esc):
        return False

with Listener(on_press = on_press, on_release = on_release) as listener:
    listener.join()

tcflush(stdin, TCIFLUSH)
예제 #38
0
 def on_release(self, key):
     tcflush(sys.stdin, TCIFLUSH)
     # print('{0} released'.format(key))
     if key == keyboard.Key.esc:
         # Stop listener
         return False
예제 #39
0
def on_message(client, userdata, msg):
    global pi
    global nextPos
    global numInUse
    global width
    global height
    global orientation
    global height
    global width
    global picPath
    global userMsg
    global curTime

    msg = msg.payload.decode('UTF-8')
    print(msg)

    for i in range(0, len(MQTT_TOPICS)):
        if (msg[0] == str(i)):
            prevA = pi[i].mA
            prevB = pi[i].mB

            pi[i].mA = msg[1]
            pi[i].mB = msg[2]
            pi[i].IMU = msg[3]
            pi[i].ip = msg.split("/")[1]
            prevTime = curTime
            curTime = msg.split("/")[2]
            pauseState = msg.split("/")[3]
            print(pi[i].ip)

            if (prevA != pi[i].mA):
                print("A change: " + str(i))
                if (pi[i].IMU == "1" or pi[i].IMU == "2"):
                    nextPos = str(pi[i].posX + 1) + str(pi[i].posY)
                    if (pi[i].posX + 1 >= width):
                        width = width + 1
                elif (pi[i].IMU == "3" or pi[i].IMU == "4"):
                    nextPos = str(pi[i].posX) + str(pi[i].posY + 1)
                    if (pi[i].posY + 1 >= height):
                        height = height + 1
            elif (prevB != pi[i].mB):
                print("B change: " + str(i))
                if (pi[i].IMU == "1" or pi[i].IMU == "2"):
                    nextPos = str(pi[i].posX) + str(pi[i].posY + 1)
                    if (pi[i].posY + 1 >= height):
                        height = height + 1
                elif (pi[i].IMU == "3" or pi[i].IMU == "4"):
                    nextPos = str(pi[i].posX + 1) + str(pi[i].posY)
                    if (pi[i].posX + 1 >= width):
                        width = width + 1

            if (numInUse == 0 and nextPos == "nn"):
                pi[i].inUse = True
                numInUse = numInUse + 1
                height = 1
                width = 1
                if (pi[i].IMU == "1" or pi[i].IMU == "2"):
                    orientation = "h"
                elif (pi[i].IMU == "3" or pi[i].IMU == "4"):
                    orientation = "v"

                fileTransfer(height, width, pi[i].IMU, orientation, picPath)
                # crop_flex.main(height, width, pi[i].IMU, orientation, picPath)
                # for counter in range(0, len(MQTT_TOPICS)):
                #     if (pi[counter].ip != "0"):
                #         filename = ("display" + str(pi[counter].posX) + str(pi[counter].posY) + ".jpg")
                #         print(filename)
                #         print(pi[counter].ip)

                #         ftptesting.main("image.jpg", pi[counter].ip, "pi", "password", "export/" + filename)

            elif (numInUse != 0 and nextPos != "nn" and pi[i].inUse == False):
                pi[i].inUse = True
                numInUse = numInUse + 1
                pi[i].posX = int(nextPos[0])
                pi[i].posY = int(nextPos[1])

                if (userMsg[5] == "v"):
                    userMsg = userMsg.replace("old", "add")
                    userMsg = userMsg.replace("play", "free")
                else:
                    userMsg = userMsg.replace("old", "new")
                    userMsg = userMsg.replace("play", "free")

                fileTransfer(height, width, pi[i].IMU, orientation, picPath)
                # crop_flex.main(height, width, pi[i].IMU, orientation, picPath)
                # for counter in range(0, len(MQTT_TOPICS)):
                #     if (pi[counter].ip != "0"):
                #         filename = ("display" + str(pi[counter].posX) + str(pi[counter].posY) + ".jpg")
                #         print(filename)
                #         print(pi[counter].ip)

                #         ftptesting.main("image.jpg", pi[counter].ip, "pi", "password", "export/" + filename)

    tcflush(sys.stdin, TCIFLUSH)
    prev = userMsg[5]

    nextStep = input(
        msg[0] +
        "Press c to continue, press q to quit everything, press n to load in new video or picture file: "
    )
    print(nextStep)
    if nextStep == "n":
        picPath = input("Please enter your new file's path: ")
        if (picPath[-3:] == "jpg"):
            userMsg = "type=pic/status=new/vid=free/prev=n"
        elif (picPath[-3:] == "mov" or picPath[-3:] == "mp4"
              or picPath[-3:] == "avi"):
            userMsg = "type=vid/status=new/vid=free/prev=n"
        fileTransfer(height, width, pi[i].IMU, orientation, picPath)

    elif nextStep == "q":
        userMsg = "type=qui/status=old/vid=play/prev=n"
        if prev == "p":
            userMsg = "type=qui/status=old/vid=play/prev=p"
        elif prev == "v":
            userMsg = "type=qui/status=old/vid=play/prev=v"
        publish.single("RPi/Master", userMsg, hostname=MQTT_BROKER)
        sys.exit()
    elif userMsg[5] == "v" and nextStep == "p":
        userMsg = userMsg.replace("free", "play")
    elif userMsg[5] == "v" and nextStep == "f":
        userMsg = "type=vid/status=old/vid=free/prev=n"
    elif nextStep == "c":
        pass

    print(userMsg)
    if prev == "p":
        userMsg = userMsg[:userMsg.find("prev=") +
                          5] + "p" + userMsg[userMsg.find("prev=") + 6:]
    elif prev == "v":
        userMsg = userMsg[:userMsg.find("prev=") +
                          5] + "v" + userMsg[userMsg.find("prev=") + 6:]

    print(userMsg)

    if (float(prevTime) > float(curTime)):
        userMsg = userMsg.split("/")[0] + "/" + userMsg.split(
            "/")[1] + "/" + userMsg.split("/")[2] + "/" + userMsg.split(
                "/")[3] + "/" + prevTime
    else:
        userMsg = userMsg.split("/")[0] + "/" + userMsg.split(
            "/")[1] + "/" + userMsg.split("/")[2] + "/" + userMsg.split(
                "/")[3] + "/" + curTime
    #if keyboard.read_key() == "n":

    # try:
    #     if keyboard.is_pressed("n"):
    #         picPath = input("Please enter your new file's path: ")
    #         if (picPath[-3: ] == "jpg"):
    #             userMsg = "type=pic/status=new/vid=/"
    #         elif (picPath[-3: ] == "mov"):
    #             userMsg = "type=vid/status=new/vid=play/"
    #         fileTransfer(height, width, pi[i].IMU, orientation, picPath)
    #     elif keyboard.is_pressed("q"):
    #         sys. exit()
    #     elif keyboard.is_pressed("p") and userMsg[5] == "v":
    #         userMsg = "type=vid/status=old/vid=play/"
    #     elif keyboard.is_pressed("f") and userMsg[5] == "v":
    #         userMsg = "type=vid/status=old/vid=free/"
    # except:
    #     pass

    # try:
    #     if keyboard.is_pressed("q"):
    #         userMsg = "type=pic/status=unload"
    #     else:
    #         userMsg = "type=pic/status=load"
    # except:
    #     print("nothing")
    printPos()
    print(userMsg)
    publish.single("RPi/Master", userMsg, hostname=MQTT_BROKER)

    if userMsg[16] == "n":
        userMsg = userMsg.replace("new", "old")
    if userMsg[16] == "a":
        userMsg = userMsg.replace("add", "old")
예제 #40
0
 def close(self, delay=0):
     if delay:
         time.sleep(delay)
         termios.tcflush(self._fd, termios.TCIFLUSH)
     termios.tcsetattr(self._fd, termios.TCSAFLUSH, self._old)
예제 #41
0
keyboard = Controller()
password = raw_input()
timings = raw_input()
print "Password = {}".format(password)
print "Timings = {}".format(timings)

password = password.split(",")
password = password[:len(password) / 2 + 1]
password = "".join(password)

print password
timings = timings.split(",")
timings = [float(a) for a in timings]
keypress = timings[:len(timings) / 2 + 1]
keyinterval = timings[len(timings) / 2 + 1:]

print "Key press time  = {}".format(keypress)
print "Key intervals = {}".format(keyinterval)

i = 0
for char in password:
    keyboard.press(char)
    sleep(keypress[i])
    keyboard.release(char)
    if (i != len(keyinterval)):
        sleep(keyinterval[i])
    i = i + 1

tcflush(stdout, TCIFLUSH)
print
예제 #42
0
    def fly(self):
        try:
            while (True):
                print('\033[2J')  # Clear screen
                print('\033[00H')  # Move cursor to top left
                print('{0}% ({1}) Command: '.format(
                    self.getBatteryPercentage(), self.getFlyingState()),
                      end='',
                      flush=True)

                # print('Command: ', end='')
                _option = input()

                if _option == 'to':  # take-off
                    print('Taking off...', end='', flush=True)

                    # self.bebop(
                    #     FlyingStateChanged(state='hovering', _policy='check') |
                    #     FlyingStateChanged(state='flying', _policy='check') |
                    #     (
                    #         GPSFixStateChanged(fixed=1, _timeout=10, _policy='check_wait')
                    #         >> (
                    #             TakeOff(_no_expect=True)
                    #             & FlyingStateChanged(state='hovering', _timeout=10, _policy='check_wait')
                    #         )
                    #     )
                    # ).wait()

                    self.bebop(TakeOff(_no_expect=True)).wait()
                    self.drone_location = self.bebop.get_state(
                        GpsLocationChanged)
                    print('Done!')
                elif _option == 'x':  # land
                    print('Landing...', end='', flush=True)
                    self.bebop(Landing()).wait()
                    print('Done!')
                elif _option == 'auto':
                    # Enable autotakeoff
                    self.bebop(UserTakeOff(1))
                elif _option == 'arm':
                    self.arm()
                elif _option == 'disarm':
                    self.disarm()
                elif _option == 'go':
                    self.moveToCoords()
                elif _option == 'm':
                    print('\033[2J')  # Clear screen
                    print('\033[00H')  # Move cursor to top left
                    print('\r{0}% Manual mode (\'esc\' to exit) '.format(
                        self.getBatteryPercentage()),
                          end='',
                          flush=True)

                    # Collect events until released
                    with keyboard.Listener(
                            on_press=self.on_press,
                            on_release=self.on_release) as listener:
                        listener.join()
                    tcflush(sys.stdin, TCIFLUSH)
                elif _option == 'quit':
                    print('Bye')
                    break
                else:
                    print('Invalid command:', _option)
        except KeyboardInterrupt:
            print('Interrupt received... Bye!')
예제 #43
0
 def accept(self):
     '''accept new chars'''
     termios.tcflush(self.fd, termios.TCIFLUSH)
     termios.tcflow(self.fd, termios.TCION)
예제 #44
0
def test_led8():
    """Test for the Pmod LED8 module.

    There are 3 tests done here:

    1. Instantiate an LED8 object on index 0 and perform some actions 
    on it, requesting user confirmation.

    2. Instantiate 8 LED objects and shift from right to left.

    3. Toggles the states of the 8 LEDs.
    
    """
    Overlay('base.bit').download()
    leds = [Pmod_LED8(led_id, index) for index in range(8)]

    led = leds[0]
    led.on()
    assert led.read() == 1
    assert user_answer_yes("\nPmod LED 0 on?")
    led.off()
    assert led.read() == 0
    assert user_answer_yes("Pmod LED 0 off?")
    led.toggle()
    assert led.read() == 1
    led.write(0)
    assert led.read() == 0
    led.write(1)
    assert led.read() == 1
    led.off()
    for led in leds:
        led.off()
    
    print("Shifting LEDs on Pmod LED8.", end='')
    print("\nPress enter to stop shifting ...", end='')
    while True:
        for led in leds:
            led.on()
            sleep(0.1)
        for led in leds:
            led.off()
            sleep(0.1)
        if sys.stdin in select.select([sys.stdin], [], [], 0)[0]:
            termios.tcflush(sys.stdin, termios.TCIOFLUSH)
            break
    assert user_answer_yes("Pmod LEDs were shifting from LD0 to LD7?")

    for led in leds:
        led.off()
    leds[0].on()
    leds[2].on()
    leds[4].on()
    leds[6].on()

    print("Toggling LEDs on Pmod LED8.", end='')
    print("\nPress enter to stop toggling ...", end='')
    while True:
        for led in leds:
            led.toggle()
        sleep(0.2)
        if sys.stdin in select.select([sys.stdin], [], [], 0)[0]:
            termios.tcflush(sys.stdin, termios.TCIOFLUSH)
            break
    for led in leds:
        led.off()
    assert user_answer_yes("Pmod LEDs were toggling?")

    del leds
예제 #45
0
    def handle_pair_request(self):
        if bluetooth_support_kitkat:
            pair_tls_ctx = ssl.SSLContext(protocol=ssl.PROTOCOL_TLSv1)
            pair_tls_ctx.set_ciphers('DHE-RSA-AES256-SHA')
            pair_tls_ctx.load_dh_params(DHPARAM_PATH)
        else:
            pair_tls_ctx = ssl.SSLContext(protocol=ssl.PROTOCOL_TLSv1_2)
            pair_tls_ctx.set_ciphers(
                'ECDHE-RSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-SHA')
            pair_tls_ctx.set_ecdh_curve('prime256v1')

        pair_tls_ctx.load_cert_chain(CERTIFICATE_PATH, RSA_PRIVATE_KEY_PATH)

        self.incoming = ssl.MemoryBIO()
        self.outgoing = ssl.MemoryBIO()
        self.tls_bio = pair_tls_ctx.wrap_bio(incoming=self.incoming,
                                             outgoing=self.outgoing,
                                             server_side=True)

        try:
            self.do_handshake()
        except ssl.SSLError as ssle:
            print_with_timestamp(
                '(Bluetooth) Failed TLS handshake pair_request: {}'.format(
                    ssle))
            return

        print_with_timestamp('(Bluetooth) Pair request from: {}\n'.format(
            self.address))
        '''I don't know how else to do this when using SSLEngine/SSL_BIO, I don't see any security
        issue with sending the length of the encrypted data in cleartext, using something like wireshark
        it's possible to see the length anyway'''
        client_cert_size = struct.unpack('>I', recvall(self.socket, 4))[0]
        client_cert_encrypted = recvall(self.socket, client_cert_size)
        client_cert = self.tls_decrypt(client_cert_encrypted)

        sha256 = hashlib.sha256(client_cert +
                                SERVER_CERT_DER).hexdigest().upper()
        sha256_format = [sha256[x:x + 2] for x in range(0, len(sha256), 2)]

        print(
            'It is very important that you verify that the following hash matches what is viewed on your phone\n'
            'It is a sha256 hash like so: sha256(client_cert + server_cert)\n\n'
            'If the hash don\'t match there could be a man-in-the-middle attack\n'
            'Or something else is not right, you should abort if they don\'t match!\n'
        )
        print(' '.join(sha256_format[:8]))
        print(' '.join(sha256_format[8:16]))
        print(' '.join(sha256_format[16:24]))
        print(' '.join(sha256_format[24:]))

        self.server_allow_pair = False
        self.client_allow_pair = False

        try:
            termios.tcflush(sys.stdin, termios.TCIFLUSH)
        except Exception:
            pass
        self.user_input_prompt = 'Enter "yes" to accept pairing or "no" to deny: '
        print('\n{}'.format(self.user_input_prompt), end='')

        threading.Thread(target=self.pair_response_thread).start()
        while not BluetoothHandler.cancel_pairing:
            ready = select.select([sys.stdin], [], [], 1)[0]
            if ready:
                user_input = sys.stdin.readline().strip()
                if user_input.casefold() == 'yes'.casefold():
                    encrypted = self.tls_encrypt(ACCEPT_PAIRING)
                    encrypted_size = struct.pack('>I', len(encrypted))
                    self.socket.sendall(encrypted_size)
                    self.socket.sendall(encrypted)
                    self.server_allow_pair = True
                    if not self.client_allow_pair:
                        print('Waiting for client response')
                    while not BluetoothHandler.cancel_pairing:
                        if self.client_allow_pair:
                            add_to_authorized_certs(client_cert)
                            break
                        else:
                            time.sleep(1)
                    break
                elif user_input.casefold() == 'no'.casefold():
                    encrypted = self.tls_encrypt(DENY_PAIRING)
                    encrypted_size = struct.pack('>I', len(encrypted))
                    self.socket.sendall(encrypted_size)
                    self.socket.sendall(encrypted)
                    print('Pairing canceled')
                    BluetoothHandler.cancel_pairing = True
                else:
                    print(self.user_input_prompt, end='', flush=True)
예제 #46
0
#!/usr/bin/python3
# -*- coding: utf-8 -*-
#
# Autobuilder
#
# Copyright (C) 2020 Elia Vicentini <*****@*****.**>
""" Starts Autobuilder program """

import autobuild
import os
import sys

from termios import tcflush, TCIOFLUSH

if __name__ == "__main__":
    try:
        autobuild.main()
    except KeyboardInterrupt:
        os.system("reset")
        tcflush(sys.stdin, TCIOFLUSH)
    except SystemExit:
        os.system("reset")
        exit(-1)

    os.system("reset")
    tcflush(sys.stdin, TCIOFLUSH)
예제 #47
0
 def reset_input_buffer(self):
     """Clear input buffer, discarding all that is in the buffer."""
     if not self.is_open:
         raise portNotOpenError
     termios.tcflush(self.fd, termios.TCIFLUSH)
예제 #48
0
    def handle_pair_request(self):
        pair_tls_ctx = ssl.SSLContext(protocol=ssl.PROTOCOL_TLSv1_2)
        pair_tls_ctx.load_cert_chain(CERTIFICATE_PATH, RSA_PRIVATE_KEY_PATH)
        pair_tls_ctx.set_ciphers(
            'ECDHE-RSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-SHA')
        pair_tls_ctx.set_ecdh_curve('prime256v1')
        pair_tls_ctx.options |= ssl.OP_SINGLE_ECDH_USE

        try:
            tls_socket = pair_tls_ctx.wrap_socket(self.request,
                                                  server_side=True)
        except ssl.SSLError as ssle:
            print_with_timestamp(
                '(TCP) Failed TLS handshake pair_request: {}'.format(ssle))
            return

        ip = self.client_address[0]
        # remove first ::ffff: if ipv4 mapped ipv6 address
        if len(ip) > 7 and ip[:7] == '::ffff:':
            ip = ip[7:]
        print_with_timestamp('(TCP) Pair request from: {}\n'.format(ip))

        client_cert_size = struct.unpack('>I', recvall(tls_socket, 4))[0]
        client_cert = recvall(tls_socket, client_cert_size)

        sha256 = hashlib.sha256(client_cert +
                                SERVER_CERT_DER).hexdigest().upper()
        sha256_format = [sha256[x:x + 2] for x in range(0, len(sha256), 2)]

        print(
            'It is very important that you verify that the following hash matches what is viewed on your phone\n'
            'It is a sha256 hash like so: sha256(client_cert + server_cert)\n\n'
            'If the hash don\'t match there could be a man-in-the-middle attack\n'
            'Or something else is not right, you should abort if they don\'t match!\n'
        )
        print(' '.join(sha256_format[:8]))
        print(' '.join(sha256_format[8:16]))
        print(' '.join(sha256_format[16:24]))
        print(' '.join(sha256_format[24:]))

        self.server_allow_pair = False
        self.client_allow_pair = False

        try:
            termios.tcflush(sys.stdin, termios.TCIFLUSH)
        except Exception:
            pass
        self.user_input_prompt = 'Enter "yes" to accept pairing or "no" to deny: '
        print('\n{}'.format(self.user_input_prompt), end='')

        threading.Thread(target=self.pair_response_thread,
                         args=(tls_socket, )).start()
        while not TCPHandler.cancel_pairing:
            ready = select.select([sys.stdin], [], [], 1)[0]
            if ready:
                user_input = sys.stdin.readline().strip()
                if user_input.casefold() == 'yes'.casefold():
                    tls_socket.sendall(ACCEPT_PAIRING)
                    self.server_allow_pair = True
                    if not self.client_allow_pair:
                        print('Waiting for client response')
                    while not TCPHandler.cancel_pairing:
                        if self.client_allow_pair:
                            add_to_authorized_certs(client_cert)
                            break
                        else:
                            time.sleep(1)
                    break
                elif user_input.casefold() == 'no'.casefold():
                    tls_socket.sendall(DENY_PAIRING)
                    print('Pairing canceled')
                    TCPHandler.cancel_pairing = True
                else:
                    print(self.user_input_prompt, end='', flush=True)
예제 #49
0
def execute_command(command):
    command = command.strip()
    lib.command_history.append(command)

    # any $variables present? replace it with tb (or global parameter) value
    newcommand = []
    parts = command.split(' ')
    for part in parts:
        if part.startswith('$'):
            # key present?
            if part[1:] in tb.keys():
                newcommand.append(tb[part[1:]])
            elif part[1:] in global_parameters.keys():
                newcommand.append(global_parameters[part[1:]])
            else:
                log.err(
                    'Key \'%s\' is not present in Temporary Base or Global Parameters.'
                    % (part[1:]))
        else:
            # escaped $?
            if part.startswith(r'\$'):
                part = part[1:]
            newcommand.append(part)
    command = ' '.join(newcommand)

    # # # # # # # # #
    # OK, what to do?
    # # # # # # # # #

    # system command
    if command.startswith('!'):
        result = cmd(command[1:])
        log.writeline(result)

    # test playground
    elif command == 'test':
        a = sorted(lib.tb['test_filesystems'][0]['packages'],
                   key=lambda x: x[0])
        b = sorted(lib.tb['sshtest_filesystems'][0]['packages'],
                   key=lambda x: x[0])
        for i in range(len(a)):
            if a[i][0] != b[i][0] or a[i][2] != b[i][2]:
                print('Difference:')
                print(a[i])
                print(b[i])
                print()

        print('-' * 20)

    # help
    elif command == 'help':
        print_help()

    # reload modules
    elif command == 'reload':
        load_modules()
        lib.prompt = ' >  '
        lib.active_module = None

    # list modules
    elif command in ['list', 'ls']:
        print_modules(list(lib.modules))

    # list modules sorted by date
    elif command in ['list date', 'ls date']:
        print_modules(list(lib.modules), order_by_date=True)

    # module search
    elif command[:7] == 'search ':
        if len(command[7:].split(' ')) == 1 and not re.search(
                r'[!|&\(\)]', command[7:]):
            # simple search, group by categories
            if command[7] in ['>', '<', '='] and len(
                    command[8:]) == 4 and command[8:].isdigit():  # date
                year = int(command[8:])
                by_year = []
                for m in lib.modules:
                    myear = int(lib.modules[m].date[:4]
                                ) if lib.modules[m].date[:4].isdigit() else 0
                    if (command[7] == '<' and myear <= year) or (
                            command[7] == '>'
                            and myear >= year) or (command[7] == '='
                                                   and myear == year):
                        by_year.append(m)
                print_modules(by_year)
                log.writeline('')

            else:  # not a year, an expression
                modules = lib.modules

                # search by module
                by_module_tmp = search_abbr(command[7:].lower(), [
                    x.lower() for x in list(modules)
                ]) + [x for x in modules if command[7:].lower() in x.lower()]
                by_module = []
                for x in by_module_tmp:
                    if x not in by_module:
                        by_module.append(x)
                if len(by_module) > 0:
                    log.attachline('By module:', log.Color.PURPLE)
                    print_modules(by_module)
                    log.writeline('')

                # search by tag
                by_tag = [
                    x for x in modules if command[7:].lower() in
                    [y.lower() for y in modules[x].tags]
                ]
                if len(by_tag) > 0:
                    log.attachline('By tags:', log.Color.PURPLE)
                    print_modules(by_tag)
                    log.writeline('')

                # search by parameter
                by_parameter = [
                    x for x in modules if command[7:].lower() in
                    [y.lower() for y in modules[x].parameters]
                ]
                if len(by_parameter) > 0:
                    log.attachline('By parameters:', log.Color.PURPLE)
                    print_modules(by_parameter)
                    log.writeline('')

                # search by author
                by_author = [
                    x for x in modules for authors in modules[x].authors
                    if command[7:].lower() in authors.name.lower()
                    or command[7:].lower() in authors.email.lower()
                    or command[7:].lower() in authors.web.lower()
                ]
                if len(by_author) > 0:
                    log.attachline('By authors:', log.Color.PURPLE)
                    print_modules(by_author)
                    log.writeline('')

                # search by dependency
                by_dependency = [
                    x for x in modules if len(
                        search_abbr(command[7:].lower(
                        ), [y.lower()
                            for y in list(modules[x].dependencies)])) > 0
                ]
                if len(by_dependency) > 0:
                    log.attachline('By dependencies:', log.Color.PURPLE)
                    print_modules(by_dependency)
                    log.writeline('')

                # search by version
                by_version = [
                    x for x in modules
                    if command[7:].lower() == modules[x].version.lower()
                ]
                if len(by_version) > 0:
                    log.attachline('By version:', log.Color.PURPLE)
                    print_modules(by_version)
                    log.writeline('')

        else:  # complicated search, use search()
            print_modules(search(command[7:]))

    # module selection
    elif command[0:4] == "use " and len(command) > 4:
        set_module(command[4:].strip())

    # back to root
    elif command == 'back':
        lib.prompt = ' >  '
        lib.active_module = None

    # use previous module
    elif command in ['prev', 'previous']:
        if lib.active_module is None:
            if len(lib.module_history) > 0:
                set_module(lib.module_history[-1])
        else:
            if len(lib.module_history) > 1:
                set_module(lib.module_history[-2])

    # module info
    elif command == 'info':
        print_module_info()

    # show options
    elif command == 'show options' or command == 'show parameters':
        print_module_info(basics=False,
                          authors=False,
                          description=False,
                          references=False,
                          tags=False,
                          dependencies=False,
                          dependent=False,
                          changelog=False)

    # show only undefined options
    elif command == 'show missing':
        print_module_info(basics=False,
                          authors=False,
                          description=False,
                          references=False,
                          tags=False,
                          dependencies=False,
                          dependent=False,
                          changelog=False,
                          missing=True)

    # show global options
    elif command == 'getg':
        maxp = max([4] + [len(x) for x in lib.global_parameters])
        log.writeline('%-*s  %s' % (maxp, 'NAME', 'VALUE'))
        log.writeline('%s  %s' % ('-' * maxp, '-' * 5), log.Color.PURPLE)
        for p in natural_sort(lib.global_parameters.keys()):
            log.writeline('%-*s  %s' % (maxp, p, lib.global_parameters[p]))

    # set global option
    elif command[:5] == 'setg ':
        command = command.replace('=', ' ')
        try:
            spaceindex = command[5:].index(' ')
        except ValueError:
            log.err('Parameters are set differently.')
            return
        # are there both key and value?
        if spaceindex <= 0 or spaceindex == len(command[5:]) - 1:
            log.err('Parameters are set differently.')
        else:
            # get key and value
            parts = [
                command[5:5 + spaceindex].strip(),
                command[5 + spaceindex:].strip()
            ]
            lib.global_parameters[parts[0]] = parts[1]
            if lib.active_module is not None and parts[
                    0] in lib.active_module.parameters:
                lib.active_module.parameters[parts[0]].value = parts[1]
            log.info('%s = %s (global)' % (parts[0], parts[1]))

    # delete global option
    elif command[:5] == 'delg ' or command[:7] == 'unsetg ':
        length = 5 if command[:5] == 'delg ' else 7
        if command[length:] in lib.global_parameters:
            log.info('Parameter %s = %s removed from global parameters.' %
                     (command[length:].strip(),
                      lib.global_parameters[command[length:]].strip()))
            del lib.global_parameters[command[length:].strip()]
        else:
            log.warn('Parameter %s not in global parameters.' %
                     (command[length:].strip()))

    # set option
    elif command[:4] == 'set ':
        command = command.replace('=', ' ')
        try:
            spaceindex = command[4:].index(' ')
        except ValueError:
            log.err('Parameters are set differently.')
            return
        if lib.active_module is None:
            log.warn('Choose a module first.')
        # are there both key and value?
        elif spaceindex <= 0 or spaceindex == len(command[4:]) - 1:
            log.err('Parameters are set differently.')
        else:
            # get key and value
            parts = [
                command[4:4 + spaceindex].strip(),
                command[4 + spaceindex:].strip()
            ]
            if parts[0] in lib.active_module.parameters:
                lib.active_module.parameters[parts[0]].value = parts[1]
                log.info('%s = %s' % (parts[0], parts[1]))
            else:
                log.warn('Non-existent parameter %s.' % (parts[0]))

    # delete option
    elif command[:4] == 'del ' or command[:6] == 'unset ':
        length = 4 if command[:4] == 'del ' else 6
        if command[length:] in lib.active_module.parameters:
            log.info(
                'Parameter %s = \'%s\' unset.' %
                (command[length:].strip(),
                 lib.active_module.parameters[command[length:]].value.strip()))
            lib.active_module.parameters[command[length:].strip()].value = ''
        else:
            log.warn('Parameter %s not in parameters.' %
                     (command[length:].strip()))

    # check
    elif command == 'check':
        m = lib.active_module
        if m is None:
            log.warn('Choose a module first.')
        # are all parameters in place?
        elif len([
                p for p in m.parameters
                if m.parameters[p].mandatory and m.parameters[p].value == ''
        ]) > 0:
            log.warn('Some parameters are undefined:')
            for x in sorted([
                    p for p in m.parameters if m.parameters[p].mandatory
                    and m.parameters[p].value == ''
            ]):
                log.warn('    %s' % x)
        else:
            # check and measure time
            start = time.time()
            check_result = m.check()
            end = time.time()
            if check_result == CHECK_SUCCESS:
                log.ok('Module will succeed.')
            if check_result == CHECK_PROBABLY:
                log.ok(
                    'Module can be executed, but we do not know whether it will succeed or not.'
                )
            elif check_result == CHECK_NOT_SUPPORTED:
                log.warn('This module does not support check.')
            elif check_result == CHECK_UNLIKELY:
                log.err('This module can be executed, but it will fail.')
            elif check_result == CHECK_FAILURE:
                log.err('This module cannot be executed.')
            log.info('Module %s has been checked in %s.' %
                     (m.name, log.show_time(end - start)))

    # run, waitfor
    elif command in ['run', 'execute'] or command.startswith('waitfor '):
        m = lib.active_module
        if m is None:
            log.warn('Choose a module first.')
        # are all parameters in place?
        elif len([
                p for p in m.parameters
                if m.parameters[p].mandatory and m.parameters[p].value == ''
        ]) > 0:
            log.warn('Some parameters are undefined:')
            for x in sorted([
                    p for p in m.parameters if m.parameters[p].mandatory
                    and m.parameters[p].value == ''
            ]):
                log.warn('    %s' % x)
        else:
            if m.check() != CHECK_FAILURE:
                # run the module
                log.info('Module %s has started.' % (m.name))

                start = time.time()
                job = m.run()  # result = None or thread
                if job is None:
                    # no thread running
                    end = time.time()
                    log.info('Module %s has terminated (%s).' %
                             (m.name, log.show_time(end - start)))

                    # flush stdin
                    if len(lib.commands) == 0 or True:
                        try:
                            import termios
                            termios.tcflush(sys.stdin, termios.TCIFLUSH)
                        except ImportError:
                            import msvcrt
                            while msvcrt.kbhit():
                                msvcrt.getch()
                        except:
                            print('Y')
                            log.err(sys.exc_info()[1])
                else:
                    # thread returned, will run in the background
                    waitfor = command[len('waitfor '):].split(
                        ' ') if command.startswith('waitfor ') else None
                    timeout = lib.active_module.parameters[
                        'TIMEOUT'].value if 'TIMEOUT' in lib.active_module.parameters else None
                    lib.scheduler.add(m.name, start, job, timeout, waitfor)
            else:  # check failed, which could be no problem for waitfor
                if command.startswith('waitfor '):
                    log.warn(
                        'Check for module %s failed, but there are modules it waits for...'
                        % (m.name))

    # print command history
    elif command == 'history':
        lib.command_history.pop()
        for h in lib.command_history:
            log.writeline(h)

    # print module history
    elif command == 'module_history':
        lib.command_history.pop()
        for h in lib.module_history:
            log.writeline(h)

    # print temporary base
    elif command == 'tb':
        maxlen = 80
        maxk = max([len(i) for i in lib.tb.items()] + [3])
        # print header
        print()
        log.attachline("%-*s  %-s" % (maxk, 'KEY', 'VALUE'))
        log.attachline('-' * maxk + '  ' + '-' * maxlen, log.Color.PURPLE)

        toescape = {x: '\\x%02x' % x for x in range(0, 32)}
        for key in natural_sort(lib.tb.keys()):
            valpart = '%s' % lib.tb[key]
            if type(valpart) == str:
                #valpart = valpart.translate(dict.fromkeys(range(0, 32), ' '))
                valpart = valpart.translate(toescape)
            if len(valpart) > maxlen:
                valpart = valpart[:maxlen - 3] + '...'
            log.attachline('%-*s  %s' % (maxk, key, valpart))

    # tb delete key
    elif command[:6] == 'tb del':
        if len(command) > 7 and command[6] == ' ':
            if command[7:] in lib.tb.keys():
                #lib.tb.delete(command[7:])
                del lib.tb[command[7:]]
        else:
            #lib.tb.delete()
            lib.tb = {}

    # tb specific value
    elif command[:3] == 'tb ':
        keys = command[3:].split(' ')
        value = lib.tb
        for key in keys:
            try:
                # if dict allow keys() and items()
                if type(value) == dict and key == 'keys()':
                    value = list(value.keys())
                    continue
                if type(value) == dict and key == 'values()':
                    value = list(value.values())
                    continue
                # if not present, try int
                if key not in value and key.isdigit():
                    key = int(key)
                value = value[key]
            except:
                log.err('Non existent key \'%s\'' % command[3:])
                break

        log.attachline(value)

        #key = command[3:]
        #if key in tb:
        #    log.attachline(tb[key])
        #else:
        #    log.err('Key \'%s\' does not exist in TB.' % (key))

    # jobs
    elif command == 'jobs':
        lib.scheduler.show()

    elif command[:10] == 'jobs kill ':
        if command[10:].strip().isdigit():
            lib.scheduler.kill(command[10:].strip())
        else:
            log.err('You must specify job ID.')

    # connections
    elif command == 'connections':
        maxt = max([4] + [len(x.typ) for x in lib.connections])
        maxc = max([9] + [len(x.description) for x in lib.connections])

        log.writeline('%*s  %-*s' % (maxt, 'TYPE', maxc, 'CONNECTOR'))
        log.writeline('%s  %s' % ('-' * maxt, '-' * maxc), log.Color.PURPLE)

        for c in lib.connections:
            log.writeline('%*s  %-*s' % (maxt, c.typ, maxc, c.description))

    elif command.startswith('connections kill '):
        newconnections = []
        c = None
        for c in lib.connections:
            if c.description == command[17:]:
                for con in c.connectors[::-1]:
                    con.close()  #TODO for SSH, but also for others?
            else:
                newconnections.append(c)
        if len(newconnections) != len(lib.connections) and c is not None:
            log.info('Connection \'%s\' killed.' % (c.description))
        lib.connections = newconnections

    # sessions
    elif command == 'session':
        log.info('Currently working with session #%d.' % lib.active_session)

    elif command[:8] == 'session ':
        newid = command[8:]
        if len(lib.scheduler.jobs) == 0:
            if newid.isdigit():
                lib.active_session = int(newid)
                log.info('Currently working with session #%d.' %
                         lib.active_session)
                if is_admin():
                    log.ok(
                        'Administrator privileges already granted on "%s".' %
                        (global_parameters['ACTIVEROOT']),
                        dbnote=DBNOTE_UNIQUE)
            elif command[8:] == 'new':
                lib.active_session = db['analysis'].get_new_session()
                log.info('Currently working with session #%d.' %
                         lib.active_session)
                if is_admin():
                    log.ok(
                        'Administrator privileges already granted on "%s".' %
                        (global_parameters['ACTIVEROOT']),
                        dbnote=DBNOTE_UNIQUE)
            else:
                log.err('Invalid session number, session #%d remains active.' %
                        lib.active_session)
        else:
            log.err('Some modules are still running in background:')
            lib.scheduler.show()

    elif command == 'authors':
        everyone = {}
        # gather author info: {(name, email): (num_of_modules, [web pages])}
        for m in lib.modules:
            for a in lib.modules[m].authors:
                if (a.name, a.email) in everyone:
                    everyone[(a.name, a.email)][0] += 1
                    if a.web not in everyone[(a.name, a.email)][1]:
                        everyone[(a.name, a.email)][1].append(a.web)
                else:
                    everyone[(a.name, a.email)] = [1, [a.web]]

        # compute column widths
        maxn = max([len(x[0]) for x in everyone] + [4])
        maxe = max([len(x[1]) for x in everyone] + [5])
        maxp = max([len(str(everyone[x][0])) for x in everyone] + [7])
        maxw = max([len(w) for x in everyone for w in everyone[x][1]] + [3])
        # print header
        log.writeline(
            '%*s  %-*s  %*s  %-*s' %
            (maxn, 'NAME', maxe, 'EMAIL', maxp, 'MODULES', maxw, 'WEB'))
        log.writeline(
            '%s  %s  %s  %s' %
            ('-' * maxn, '-' * maxe, '-' * maxp, '-' * maxw), log.Color.PURPLE)
        # sort by number of plugins, then by name
        keys = sorted(sorted(list(everyone), key=lambda x: x[0]),
                      key=lambda x: everyone[x][0],
                      reverse=True)
        # print authors
        for a in everyone:
            wcounter = 0
            for w in everyone[a][1]:
                if wcounter == 0:
                    log.writeline('%*s  %-*s  %*d  %-*s' %
                                  (maxn, a[0], maxe, a[1], maxp,
                                   everyone[a][0], maxw, w))
                else:
                    log.writeline('%*s  %-*s  %*s  %*s' %
                                  (maxn, '', maxe, '', maxp, '', maxw, w))

                wcounter += 1

    # dictionaries
    elif command in ['dict', 'dicts', 'dictionary', 'dictionaries']:

        log.info('Wait for it...')
        dicts_summary = db['dict'].get_summary()
        print(dicts_summary)
        """if len(dicts) > 0:
            # compute column width
            maxd = max([len(x) for x in dicts] + [10])
            maxn = max([len(str(len(dicts[x]))) for x in dicts] + [5])
            
            # print header
            log.writeline('%*s  %-*s' % (maxd, 'DICTIONARY', maxn, 'WORDS'))
            log.writeline('%s  %s' % ('-' * maxd, '-' * maxn), log.Color.PURPLE)
            
            # print entries
            keys = sorted(list(dicts))
            for k in keys:
                log.writeline('%*s  %d' % (maxd, k, len(dicts[k])))
            log.writeline()"""

    # empty, new line, comment
    elif command == '' or command[0] == '#':
        lib.command_history.pop()
        pass

    # force exit (no prompt)
    elif command.lower() == 'force_exit':
        exit_program(None, None)

    # exit
    elif command.lower() in QUIT_STRINGS:
        log.warn('Do you really want to quit? ', end=False)
        if positive(input()):
            exit_program(None, None)
        else:
            lib.command_history.pop()

    # something else
    else:
        log.warn('Bad command "%s".' % (command))
        lib.command_history.pop()
예제 #50
0
 def flushOutput(self):
     """Clear output buffer, aborting the current output and
     discarding all that is in the buffer."""
     if self.fd is None:
         raise portNotOpenError
     termios.tcflush(self.fd, TERMIOS.TCOFLUSH)
예제 #51
0
def ask_save(save_list,
             savers,
             sess,
             do_ask=True,
             index_combos=None,
             failsafe=True,
             sysarg_key="--save",
             sleep=5,
             save_copy_suffix=None,
             state=None,
             label=None):
    if "--discard" in sys.argv:
        color_print("--discard given -- not saving any models", style="danger")
        return
    do_dialog = True
    if index_combos is None:
        index_combos = []
    sysarg_val = util.get_valv(sysarg_key, "ask")
    if sysarg_val != "ask":
        do_dialog = False
        tmp_index_combos = [("All", list(range(len(save_list)))),
                            ("None", [])] + index_combos
        combo_firsts = [nme[0].lower() for nme, _ in tmp_index_combos]
        sysarg_value_idx = sys.argv.index(sysarg_key) + 1
        sysarg_value = sys.argv[sysarg_value_idx]
        if sysarg_value in combo_firsts:
            restore_combo = tmp_index_combos[combo_firsts.index(sysarg_value)]
            tcflush(sys.stdin, TCIFLUSH)
            saving_msg = f"SAVING combo '{restore_combo[0]}'."
            if "--rush" not in sys.argv:
                saving_msg += f"Enter any key (within {sleep} seconds) to prevent, and get dialog"
            color_print(saving_msg, style="warning")
            start = time.time()
            nb_char = ""
            while True and "--rush" not in sys.argv:
                nb_char = util.read_stdin()
                # if start+sleep <= time.time() or nb_char:
                if start + sleep <= time.time() or nb_char:
                    if nb_char:
                        print(nb_char)
                    break
                time.sleep(0.1)
            if nb_char:
                do_dialog = True
                color_print(f"Not saving. Getting dialog", style="notice")
            else:
                names_to_save = [save_list[i] for i in restore_combo[1]]
        else:
            try:
                raise click.BadParameter(
                    f"Cannot find combo starting with {sysarg_value} ({sysarg_key})"
                )
            except click.BadParameter as e:
                if not failsafe:
                    raise
                else:
                    print(e)
                    do_dialog = True
    if do_dialog:
        tcflush(sys.stdin, TCIFLUSH)
        _, names_to_save = util.ask_list(save_list,
                                         message="Choose models to save",
                                         names=None,
                                         allow_all=True,
                                         allow_none=True,
                                         index_combos=index_combos,
                                         failsafe=failsafe)
    for saver_name in names_to_save:
        print(f"Saving {saver_name}")
        savers[saver_name].do_save(sess,
                                   save_dir=None,
                                   label=label,
                                   state=state,
                                   suffix=save_copy_suffix)
        # color_print("ONLY PRETENDING TO SAVE (NO SAVING ACTUALLY HAPPENED!)", style="danger")
        # if suffix:
        #
        # else:
        #     savers[saver_name].do_save(sess)
        #
        # copytree(src=savers[saver_name].save_directory,dst=savers[saver_name].save_directory)
    if not names_to_save:
        print("Not saving...")
예제 #52
0
 def flushInput(self):
     """Clear input buffer, discarding all that is in the buffer."""
     if self.fd is None:
         raise portNotOpenError
     termios.tcflush(self.fd, TERMIOS.TCIFLUSH)
예제 #53
0
def cave_2(items):
    """Cave2 Zone."""
    # current_location = [5, 2]
    directions = ["w"]
    destinations = [0, 0, 0, cave_1]
    print_pause("\nDark Cave Interior\n", 2)
    print_pause("A dank miasma fills the cave\n", 2)
    if 'Troll Tooth' not in items:
        print_pause(
            "Out from nowhere a giant troll"
            " appears and lunges at you!\n", 2.5)
        if 'Sword' not in items:
            print_pause(
                "You are totally helpless"
                " with no way to defend yourself", 2.5)
            print_pause("One big crunch and your lights go out...", 4)
            replay()
        else:
            print_pause(
                "In an instant you draw "
                "your sword to defend yourself!\n", 2.5)
            print_pause(
                "The troll wasn't expecting armed prey! You manage to"
                " stab\nhim as he lunges at you.\n", 2.5)
            print_pause("The troll howls in pain!\n", 2.5)
            print_pause("He seems to be regenerating! Oh no!\n", 4)
            if 'Torch' not in items:
                print_pause(
                    "After a long battle of "
                    "attrition the troll\ngets the better of you", 2.5)
                print_pause("\nOne big crunch and your lights go out...", 4)
                replay()
            else:
                print_pause(
                    "Thinking quickly, you shove "
                    "your torch into the trolls face\n", 2.5)
                print_pause(
                    "That did the trick! The troll bursts into flames"
                    " and falls \nlifelessly to the ground\n", 2.5)
                print_pause("You decide to take a tooth as a souveneir\n", 5)
                print_pause("You acquired 'Troll Tooth'\n", 2.5)
                items.append('Troll Tooth')
                cave_1(items)
    elif 'Stinky Mushroom' not in items:
        print_pause("Your Torch lights the way\n", 2)
        if 'Gloves' not in items:
            print_pause("You see giant, stinky mushroom\n", 2)
        else:
            print_pause(
                "You see giant, stinky mushroom."
                " This must be the one the witch wanted.\n", 2)
        termios.tcflush(sys.stdin, termios.TCIOFLUSH)
        os.system("stty echo")
        choice = valid_input("Pick it? Y/N\n", ["y", "n"])
        if choice == "y" and 'Gloves' not in items:
            os.system("stty -echo")
            print_pause(
                "You immediately regret your decision.\n You start to "
                "feel sick and your vision starts to fade away...", 3)
            replay()
        elif choice == "y" and 'Gloves' in items:
            os.system("stty -echo")
            print_pause(
                "You carefully harvest the "
                "dangerous mushroom for the witch\n", 2)
            print_pause("You acquired 'Stinky Mushroom'\n", 2)
            items.append('Stinky Mushroom')
        elif choice == "n" and 'Gloves' not in items:
            print_pause("Good call, that thing looks dangerous\n", 2)
        elif choice == "n" and 'Gloves' in items:
            print_pause("Well, the witch is waiting...\n", 2)
            cave_1(items)
    choose_direction(directions, destinations, items)
예제 #54
0
    def run(self, tmp=None, task_vars=None):
        ''' run the pause action module '''
        if task_vars is None:
            task_vars = dict()

        result = super(ActionModule, self).run(tmp, task_vars)
        del tmp  # tmp no longer has any effect

        duration_unit = 'minutes'
        prompt = None
        seconds = None
        echo = True
        echo_prompt = ''
        result.update(
            dict(changed=False,
                 rc=0,
                 stderr='',
                 stdout='',
                 start=None,
                 stop=None,
                 delta=None,
                 echo=echo))

        if not set(self._task.args.keys()) <= set(self.PAUSE_TYPES):
            result['failed'] = True
            result[
                'msg'] = "Invalid argument given. Must be one of: %s" % ", ".join(
                    self.PAUSE_TYPES)
            return result

        # Should keystrokes be echoed to stdout?
        if 'echo' in self._task.args:
            echo = self._task.args['echo']
            if not type(echo) == bool:
                result['failed'] = True
                result[
                    'msg'] = "'%s' is not a valid setting for 'echo'." % self._task.args[
                        'echo']
                return result

            # Add a note saying the output is hidden if echo is disabled
            if not echo:
                echo_prompt = ' (output is hidden)'

        # Is 'prompt' a key in 'args'?
        if 'prompt' in self._task.args:
            prompt = "[%s]\n%s%s:" % (self._task.get_name().strip(),
                                      self._task.args['prompt'], echo_prompt)
        else:
            # If no custom prompt is specified, set a default prompt
            prompt = "[%s]\n%s%s:" % (self._task.get_name().strip(),
                                      'Press enter to continue', echo_prompt)

        # Are 'minutes' or 'seconds' keys that exist in 'args'?
        if 'minutes' in self._task.args or 'seconds' in self._task.args:
            try:
                if 'minutes' in self._task.args:
                    # The time() command operates in seconds so we need to
                    # recalculate for minutes=X values.
                    seconds = int(self._task.args['minutes']) * 60
                else:
                    seconds = int(self._task.args['seconds'])
                    duration_unit = 'seconds'

            except ValueError as e:
                result['failed'] = True
                result[
                    'msg'] = u"non-integer value given for prompt duration:\n%s" % to_text(
                        e)
                return result

        ########################################################################
        # Begin the hard work!

        start = time.time()
        result['start'] = to_text(datetime.datetime.now())
        result['user_input'] = b''

        fd = None
        old_settings = None
        try:
            if seconds is not None:
                if seconds < 1:
                    seconds = 1

                # setup the alarm handler
                signal.signal(signal.SIGALRM, timeout_handler)
                signal.alarm(seconds)

                # show the timer and control prompts
                display.display("Pausing for %d seconds%s" %
                                (seconds, echo_prompt))
                display.display(
                    "(ctrl+C then 'C' = continue early, ctrl+C then 'A' = abort)\r"
                ),

                # show the prompt specified in the task
                if 'prompt' in self._task.args:
                    display.display(prompt)

            else:
                display.display(prompt)

            # save the attributes on the existing (duped) stdin so
            # that we can restore them later after we set raw mode
            fd = None
            try:
                if PY3:
                    stdin = self._connection._new_stdin.buffer
                else:
                    stdin = self._connection._new_stdin
                fd = stdin.fileno()
            except (ValueError, AttributeError):
                # ValueError: someone is using a closed file descriptor as stdin
                # AttributeError: someone is using a null file descriptor as stdin on windoez
                stdin = None
            if fd is not None:
                if isatty(fd):
                    old_settings = termios.tcgetattr(fd)
                    tty.setraw(fd)

                    # Enable a few things turned off by tty.setraw()
                    # ICANON -> Allows characters to be deleted and hides things like ^M.
                    # ICRNL -> Makes the return key work when ICANON is enabled, otherwise
                    #          you get stuck at the prompt with no way to get out of it.
                    # See man termios for details on these flags
                    if not seconds:
                        new_settings = termios.tcgetattr(fd)
                        new_settings[0] = new_settings[0] | termios.ICRNL
                        new_settings[3] = new_settings[3] | termios.ICANON
                        termios.tcsetattr(fd, termios.TCSANOW, new_settings)

                        if echo:
                            # Enable ECHO since tty.setraw() disables it
                            new_settings = termios.tcgetattr(fd)
                            new_settings[3] = new_settings[3] | termios.ECHO
                            termios.tcsetattr(fd, termios.TCSANOW,
                                              new_settings)

                    # flush the buffer to make sure no previous key presses
                    # are read in below
                    termios.tcflush(stdin, termios.TCIFLUSH)
            while True:
                try:
                    if fd is not None:
                        key_pressed = stdin.read(1)

                        if seconds:
                            if key_pressed == b'\x03':
                                raise KeyboardInterrupt

                    if not seconds:
                        if fd is None or not isatty(fd):
                            display.warning(
                                "Not waiting from prompt as stdin is not interactive"
                            )
                            break
                        # read key presses and act accordingly
                        if key_pressed in (b'\r', b'\n'):
                            break
                        else:
                            result['user_input'] += key_pressed

                except KeyboardInterrupt:
                    if seconds is not None:
                        signal.alarm(0)
                    display.display(
                        "Press 'C' to continue the play or 'A' to abort \r"),
                    if self._c_or_a(stdin):
                        break
                    else:
                        raise AnsibleError('user requested abort!')

        except AnsibleTimeoutExceeded:
            # this is the exception we expect when the alarm signal
            # fires, so we simply ignore it to move into the cleanup
            pass
        finally:
            # cleanup and save some information
            # restore the old settings for the duped stdin fd
            if not (None in (fd, old_settings)) and isatty(fd):
                termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)

            duration = time.time() - start
            result['stop'] = to_text(datetime.datetime.now())
            result['delta'] = int(duration)

            if duration_unit == 'minutes':
                duration = round(duration / 60.0, 2)
            else:
                duration = round(duration, 2)
            result['stdout'] = "Paused for %s %s" % (duration, duration_unit)

        result['user_input'] = to_text(result['user_input'],
                                       errors='surrogate_or_strict')
        return result
예제 #55
0
 def flushInput(self):
     """clear input queue"""
     if not self.fd:
         raise portNotOpenError
     termios.tcflush(self.fd, TERMIOS.TCIFLUSH)
예제 #56
0
 def forgetinput(self):
     termios.tcflush(self.input_fd, termios.TCIFLUSH)
예제 #57
0
 def flush(self):
     termios.tcflush(sys.stdin, termios.TCIOFLUSH)
예제 #58
0
 def getch(self):
     termios.tcflush(0, termios.TCIFLUSH)  # XXX Leave this in?
     return os.read(self._fd, 1)
예제 #59
0
 def flushOutput(self):
     """flush output"""
     if not self.fd:
         raise portNotOpenError
     termios.tcflush(self.fd, TERMIOS.TCOFLUSH)
예제 #60
0
def serial(path,
           baud=115200,
           bits=8,
           parity=False,
           oddparity=False,
           stopbits=1,
           local=True,
           crtscts=False,
           blocking=True):
    fd = os.open(
        path, os.O_RDWR | os.O_NOCTTY | (os.O_NONBLOCK if not blocking else 0))
    if fd == -1:
        raise Exception("Opening device '%s' failed" % path)

    current = termios.tcgetattr(fd)
    # ignore break,  don't translate \r -> \n
    current[0] |= termios.IGNBRK
    current[0] &= ~(termios.ICRNL | termios.BRKINT | termios.IMAXBEL)
    # disable OPOST
    current[1] &= ~termios.OPOST
    # disable \n -> \r
    current[1] &= ~termios.ONLCR
    # disable echo
    current[3] &= ~(termios.ECHO | termios.ECHOE | termios.ECHOK
                    | termios.ECHOCTL)
    # enable 'cbreak'
    current[3] &= ~termios.ICANON
    # disable signals
    current[3] &= ~termios.ISIG

    termios.tcflush(fd, termios.TCIFLUSH)
    termios.tcsetattr(fd, termios.TCSANOW, current)
    current = termios.tcgetattr(fd)

    # baud rate
    if not (stopbits == 1 or stopbits == 2):
        raise Exception("Invalid number of stop bits (only 1 or 2 is valid).")
    current[2] = (current[2]
                  & ~termios.CSTOPB) | (termios.CSTOPB if stopbits == 2 else 0)
    current[2] = (current[2]
                  & ~termios.PARENB) | (termios.PARENB if parity else 0)
    current[2] = (current[2]
                  & ~termios.PARODD) | (termios.PARODD if oddparity else 0)

    # get speed_t value
    new_speed = None
    if "B%d" % baud in termios.__dict__:
        new_speed = termios.__dict__["B%d" % baud]
    if new_speed is None:
        raise Exception("Invalid baud rate '%d'" % baud)
    current[4] = new_speed
    current[5] = new_speed

    termios.tcflush(fd, termios.TCIFLUSH)
    termios.tcsetattr(fd, termios.TCSANOW, current)
    current = termios.tcgetattr(fd)

    # flow
    current[2] = (current[2]
                  & ~termios.CLOCAL) | (termios.CLOCAL if local else 0)
    current[2] = (current[2]
                  & ~termios.CRTSCTS) | (termios.CRTSCTS if crtscts else 0)

    termios.tcflush(fd, termios.TCIFLUSH)
    termios.tcsetattr(fd, termios.TCSANOW, current)

    return fd