예제 #1
0
 def flush(self):
     """\
     Flush of file like objects. In this case, wait until all data
     is written.
     """
     if not self.is_open:
         raise portNotOpenError
     termios.tcdrain(self.fd)
예제 #2
0
    def flush_output(self):
        """Flush output buffer on serial port."""

        if sys.platform.startswith("win"):
            self.ser.flushOutput()
            return

        termios.tcdrain(self.fd)
예제 #3
0
 def flush(self):
     """\
     Flush of file like objects. In this case, wait until all data
     is written.
     """
     if not self.is_open:
         raise portNotOpenError
     termios.tcdrain(self.fd)
예제 #4
0
 def restore(cls, *_whatever):
     if sys.stderr.isatty():
         termios.tcdrain(sys.stderr.fileno())
     if sys.stdout.isatty():
         termios.tcdrain(sys.stdout.fileno())
     if sys.stdin.isatty():
         termios.tcflush(sys.stdin.fileno(), termios.TCIOFLUSH)
     if cls.old_tcattrs:
         termios.tcsetattr(sys.stdin.fileno(), termios.TCSANOW,
                           cls.old_tcattrs)
예제 #5
0
def doGo(options, param):
  checkDevOpen(options)
  os.write(options.dev, "G%x#" % tuple(param))

  # This tcdrain() seems to be necessary on some machines when the 'go'
  # command is the last one on the command line. It seems that the command
  # isn't fully sent by the time the program exits.
  termios.tcdrain(options.dev)

  return
예제 #6
0
    def flush(self):
        try:
            os.write(self._fd_out, self._out_buffer)
        except BrokenPipeError:
            # this can happen if stdout is redirected to a program and the
            # program exits before termpixels. We switch to TTY output so that
            # the terminal can be reset if necessary.
            self._fd_out = self._fd_out_tty

        self._out_buffer.clear()
        termios.tcdrain(self._fd_out_tty)
예제 #7
0
def read_error_status(board):
    # To do : check the arguments
    dest = board << 2
    wrtbuf = [PRE, CMD_GET_ERROR, dest, POST, POST, POST, POST]
    os.write(filehandle, bytes(wrtbuf))
    termios.tcdrain(filehandle)
    ok, data = read_uart(4)
    if (not ok):  # or wrtbuf[0]!=CMD_GET_ERROR or wrtbuf[1]!=dest) :
        return -1
    val = (data[2] << 8) | data[3]
    return val
예제 #8
0
파일: gertbot.py 프로젝트: oatmeal3000/qupy
def read_error_status(board):
   # To do : check the arguments
   dest = board<<2
   wrtbuf = [PRE, CMD_GET_ERROR, dest, POST, POST, POST, POST]
   os.write(filehandle,bytes(wrtbuf))
   termios.tcdrain(filehandle)
   ok , data = read_uart(4)
   if (not ok) : # or wrtbuf[0]!=CMD_GET_ERROR or wrtbuf[1]!=dest) :
     return -1
   val = (data[2]<<8) | data[3]
   return val
예제 #9
0
파일: gertbot.py 프로젝트: oatmeal3000/qupy
def read_adc(board,adc) :            
   # To do : check the arguments
   dest = (board<<2) | adc
   wrtbuf = [PRE, CMD_GET_ADC, dest, POST, POST, POST, POST]
   os.write(filehandle,bytes(wrtbuf))
   termios.tcdrain(filehandle)
   ok , data = read_uart(4)
   if (not ok) : # or data[0]!=CMD_GET_ERROR or data[1]!=dest) :
      return -1
   ival = (data[2]<<8) | data[3]
   ## convert integer to float in range 0..3.3V
   return ival*(3.3/4095.0)
예제 #10
0
def read_adc(board, adc):
    # To do : check the arguments
    dest = (board << 2) | adc
    wrtbuf = [PRE, CMD_GET_ADC, dest, POST, POST, POST, POST]
    os.write(filehandle, bytes(wrtbuf))
    termios.tcdrain(filehandle)
    ok, data = read_uart(4)
    if (not ok):  # or data[0]!=CMD_GET_ERROR or data[1]!=dest) :
        return -1
    ival = (data[2] << 8) | data[3]
    ## convert integer to float in range 0..3.3V
    return ival * (3.3 / 4095.0)
예제 #11
0
def get_version(board):
    dest = (board << 2)
    wrtbuf = [0xA0, CMD_VERSION, dest, POST, POST, POST, POST]
    os.write(filehandle, bytearray(wrtbuf))
    termios.tcdrain(filehandle)
    ok, data = read_uart(4)
    if (not ok):  # or wrtbuf[0]!=CMD_GET_ERROR or wrtbuf[1]!=dest) :
        return 0
    # convert xx.yy into xx*100+yy
    # thus version 2.5 comes out as 205
    val = data[2] * 100 + data[3]
    return val
예제 #12
0
    def flush(self):
        """Flush the write buffer of the serial port, blocking until all bytes
        are written.

        Raises:
            SerialError: if an I/O or OS error occurs.

        """
        try:
            termios.tcdrain(self._fd)
        except termios.error as e:
            raise SerialError(e.errno, "Flushing serial port: " + e.strerror)
예제 #13
0
    def flush(self):
        """Flush the write buffer of the serial port, blocking until all bytes
        are written.

        Raises:
            SerialError: if an I/O or OS error occurs.

        """
        try:
            termios.tcdrain(self._fd)
        except termios.error as e:
            raise SerialError(e.errno, "Flushing serial port: " + e.strerror)
예제 #14
0
def get_version(board) :
   dest = (board<<2)
   wrtbuf = [0xA0, CMD_VERSION, dest, POST, POST, POST, POST]
   os.write(filehandle,bytearray(wrtbuf))
   termios.tcdrain(filehandle)
   ok , data = read_uart(4)
   if (not ok) : # or wrtbuf[0]!=CMD_GET_ERROR or wrtbuf[1]!=dest) :
     return 0
   # convert xx.yy into xx*100+yy 
   # thus version 2.5 comes out as 205
   val = data[2]*100 + data[3]
   return val
예제 #15
0
파일: gertbot.py 프로젝트: oatmeal3000/qupy
def read_inputs(board) :
#  GB_CHECKN(board>=0 && board<=3, "read_inputs illegal board\n")
   dest = (board << 2)
   wrtbuf = [PRE, CMD_READIO, dest, POST, POST, POST, POST, POST]
   os.write(filehandle,bytes(wrtbuf))
   termios.tcdrain(filehandle)
   ok , rec_data = read_uart(5)
   if (not ok) : # or data[0]!=CMD_GET_ADC or data[1]!=dest) :
      return -1
   i_value  = rec_data[4]
   i_value |= rec_data[3]<<8
   i_value |= rec_data[2]<<16
   return i_value
예제 #16
0
def read_inputs(board):
    #  GB_CHECKN(board>=0 && board<=3, "read_inputs illegal board\n")
    dest = (board << 2)
    wrtbuf = [PRE, CMD_READIO, dest, POST, POST, POST, POST, POST]
    os.write(filehandle, bytes(wrtbuf))
    termios.tcdrain(filehandle)
    ok, rec_data = read_uart(5)
    if (not ok):  # or data[0]!=CMD_GET_ADC or data[1]!=dest) :
        return -1
    i_value = rec_data[4]
    i_value |= rec_data[3] << 8
    i_value |= rec_data[2] << 16
    return i_value
예제 #17
0
 def thread_send_stop(self):
     if (self.fd > 0):
         if ENABLE_RTS_LINE:
             self.portLock.acquire()
             if ENABLE_TCDRAIN:
                 termios.tcdrain(self.fd)
             time.sleep(SERIAL_PORT_COOLDOWN_TIME)
             # set RTS to off
             self.setRTS(False)
             self.portLock.release()
     # use the message queue to send self.sentPackets
     if self.msgQueue is not None:
         self.msgQueue.put((self.txThread.threadID, self.sentPackets, REPORT_DATA_RECIEVED))
예제 #18
0
 def _restore_attrs(self):
     new_attrs = termios.tcgetattr(self.fd)
     if new_attrs == self.attrs:
         return
     warning_message("TTY flags for", self.fd.name, "changed, resetting them")
     print("Previous state", self.attrs)
     print("New state", new_attrs)
     termios.tcsetattr(self.fd, termios.TCSANOW, self.attrs)
     termios.tcdrain(self.fd)
     new_attrs = termios.tcgetattr(self.fd)
     if new_attrs != self.attrs:
         warning_message("Failed to restore TTY flags for", self.fd.name)
         print("Previous state", self.attrs)
         print("New state", new_attrs)
예제 #19
0
파일: gertbot.py 프로젝트: oatmeal3000/qupy
def get_motor_status(brd,mot) :
   id = (brd<<2) | mot
   wrtbuf = [PRE, CMD_MOT_STATUS, id, POST, POST, POST, POST, POST, POST]
   os.write(filehandle,bytes(wrtbuf))
   # returns 6 bytes:
   # ID, CMD, move,
   # step_count:MS, step_count:MM, step_count:LS
   termios.tcdrain(filehandle)
   ok , rec_data = read_uart(6)
   if (not ok) : # or rec_data[0]!=CMD_MOT_STATUS or rec_data[1]!=dest) :
      return []
   motor_data = [0]*2
   motor_data[0] = rec_data[2] & 0x0F
   motor_data[1] =(rec_data[3]<<16) + (rec_data[4]<<8)+rec_data[5]
   return motor_data 
예제 #20
0
def get_motor_status(brd, mot):
    id = (brd << 2) | mot
    wrtbuf = [PRE, CMD_MOT_STATUS, id, POST, POST, POST, POST, POST, POST]
    os.write(filehandle, bytes(wrtbuf))
    # returns 6 bytes:
    # ID, CMD, move,
    # step_count:MS, step_count:MM, step_count:LS
    termios.tcdrain(filehandle)
    ok, rec_data = read_uart(6)
    if (not ok):  # or rec_data[0]!=CMD_MOT_STATUS or rec_data[1]!=dest) :
        return []
    motor_data = [0] * 2
    motor_data[0] = rec_data[2] & 0x0F
    motor_data[1] = (rec_data[3] << 16) + (rec_data[4] << 8) + rec_data[5]
    return motor_data
예제 #21
0
 def _open(self, port, speed):
     self._fd = os.open(port, os.O_RDWR | os.O_NOCTTY | os.O_NONBLOCK)
     self.port = os.fdopen(self._fd, "r+b", buffering=0)
     iflag, oflag, cflag, lflag, ispeed, ospeed, cc = termios.tcgetattr(self._fd)
     iflag = termios.IGNBRK | termios.IGNPAR
     oflag = 0
     cflag |= termios.CLOCAL | termios.CREAD | termios.CS8
     lflag = 0
     ispeed = ospeed = getattr(termios, "B%s" % speed)
     cc[termios.VMIN] = 1
     cc[termios.VTIME] = 0
     termios.tcsetattr(self._fd, termios.TCSANOW, [iflag, oflag, cflag, lflag, ispeed, ospeed, cc])
     termios.tcdrain(self._fd)
     termios.tcflush(self._fd, termios.TCOFLUSH)
     termios.tcflush(self._fd, termios.TCIFLUSH)
예제 #22
0
 def set_baud(self, baud):
     iflag, oflag, cflag, lflag, ispeed, ospeed, cc = \
         termios.tcgetattr(self._fd)
     iflag = termios.IGNBRK | termios.IGNPAR
     oflag = 0
     cflag |= termios.CLOCAL | termios.CREAD | termios.CS8
     lflag = 0
     ispeed = ospeed = getattr(termios, "B"+str(baud))
     cc[termios.VMIN] = 1
     cc[termios.VTIME] = 0
     termios.tcsetattr(self._fd, termios.TCSANOW, [
         iflag, oflag, cflag, lflag, ispeed, ospeed, cc])
     termios.tcdrain(self._fd)
     termios.tcflush(self._fd, termios.TCOFLUSH)
     termios.tcflush(self._fd, termios.TCIFLUSH)
     logger.debug("baud rate set to".format(baud))
예제 #23
0
 def _open(self, port, speed):
     self._fd = os.open(port, os.O_RDWR | os.O_NOCTTY | os.O_NONBLOCK)
     self.port = os.fdopen(self._fd, "r+b", buffering=0)
     iflag, oflag, cflag, lflag, ispeed, ospeed, cc = \
       termios.tcgetattr(self._fd)
     iflag = termios.IGNBRK | termios.IGNPAR
     oflag = 0
     cflag |= termios.CLOCAL | termios.CREAD | termios.CS8
     lflag = 0
     ispeed = ospeed = getattr(termios, "B%s" % speed)
     cc[termios.VMIN] = 1
     cc[termios.VTIME] = 0
     termios.tcsetattr(self._fd, termios.TCSANOW,
                       [iflag, oflag, cflag, lflag, ispeed, ospeed, cc])
     termios.tcdrain(self._fd)
     termios.tcflush(self._fd, termios.TCOFLUSH)
     termios.tcflush(self._fd, termios.TCIFLUSH)
예제 #24
0
파일: gertbot.py 프로젝트: oatmeal3000/qupy
def get_motor_missed(brd,mot) :
   id = (brd<<2) | mot
   wrtbuf = [PRE, CMD_MOT_MISSED, id, POST, POST, POST, POST, POST, POST]
   os.write(filehandle,bytes(wrtbuf))
   # returns 8 bytes:
   # ID, CMD,
   # missed:MS, missed:MM, missed:LS
   # three times 0 
   termios.tcdrain(filehandle)
   ok , rec_data = read_uart(8)
   if (not ok) : # or rec_data[0]!=CMD_MOT_MISSED or rec_data[1]!=dest) :
      return []
   motor_data = [0]*2
   motor_data[0] =(rec_data[2]<<16) + (rec_data[3]<<8)+rec_data[4]
   # Next should be zero 
   motor_data[1] =(rec_data[5]<<16) + (rec_data[6]<<8)+rec_data[7]
   return motor_data 
예제 #25
0
 def _restore_attrs(self):
     new_attrs = termios.tcgetattr(self.fd)
     if new_attrs == self.attrs:
         return
     warning_message("TTY flags for", self.fd.name, "changed, resetting them")
     print("Previous state", self.attrs)
     print("New state", new_attrs)
     try:
         termios.tcsetattr(self.fd, termios.TCSADRAIN, self.attrs)
         termios.tcdrain(self.fd)
     except Exception as e:
         warning_message("Error while restoring TTY flags:", e)
     new_attrs = termios.tcgetattr(self.fd)
     if new_attrs != self.attrs:
         warning_message("Failed to restore TTY flags for", self.fd.name)
         print("Previous state", self.attrs)
         print("New state", new_attrs)
예제 #26
0
def get_motor_missed(brd, mot):
    id = (brd << 2) | mot
    wrtbuf = [PRE, CMD_MOT_MISSED, id, POST, POST, POST, POST, POST, POST]
    os.write(filehandle, bytes(wrtbuf))
    # returns 8 bytes:
    # ID, CMD,
    # missed:MS, missed:MM, missed:LS
    # three times 0
    termios.tcdrain(filehandle)
    ok, rec_data = read_uart(8)
    if (not ok):  # or rec_data[0]!=CMD_MOT_MISSED or rec_data[1]!=dest) :
        return []
    motor_data = [0] * 2
    motor_data[0] = (rec_data[2] << 16) + (rec_data[3] << 8) + rec_data[4]
    # Next should be zero
    motor_data[1] = (rec_data[5] << 16) + (rec_data[6] << 8) + rec_data[7]
    return motor_data
예제 #27
0
def get_motor_config(brd,mot) :
   id = (brd<<2) | mot
   wrtbuf = [PRE, CMD_MOT_CONFIG, id, POST, POST, POST, POST, POST,
             POST, POST, POST, POST, POST, POST, POST, POST]
   os.write(filehandle,bytes(wrtbuf))
   termios.tcdrain(filehandle)
   ok , rec_data = read_uart(13)
   if (not ok) : # or rec_data[0]!=CMD_MOT_CONFIG or rec_data[1]!=dest) :
      return []
   motor_data = [0]*8
   motor_data[0] = rec_data[2] & 0x1F
   motor_data[1] = rec_data[3] & 0xF
   motor_data[2] = rec_data[3]>>4
   motor_data[3] =(rec_data[4]<<16) + (rec_data[5]<<8)+rec_data[6]
   motor_data[4] =(rec_data[7]<<8)  + rec_data[8]
   motor_data[5] =(rec_data[9] & 0x0F)
   motor_data[6] =(rec_data[9] >>4)
   motor_data[7] =(rec_data[10] & 0x0F)
   return motor_data
예제 #28
0
def _send_cmd(cmd):
    # Flush data path all the way to nestedlog server.
    #
    # These should be no-ops, since stdout/stderr are a character device
    # rather than pipes.
    sys.stdout.flush()
    sys.stderr.flush()
    # Synchronously flush to nestedlog-helper CUSE server, which will
    # synchronously flush to main nestedlog server.
    termios.tcdrain(1)

    sock_path = os.environ[SOCK_ENV_VAR]
    client_sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
    client_sock.connect(sock_path)
    client_sock.sendall(cmd.encode('utf-8'))
    response = client_sock.recv(1)
    client_sock.close()
    if response != b'0':
        raise Exception('nestedlog server command failed')
예제 #29
0
def quad_read(board, channel):
    #  GB_CHECK(board>=0  && board<=3,   "quad_read illegal board\n");
    #  GB_CHECK(gb_motor[board][channel].flags&QUAD_ON,"quad_read not in quadrature mode\n");
    dest = (board << 2) | channel
    wrtbuf = [
        PRE, CMD_QUAD_READ, dest, POST, POST, POST, POST, POST, POST, POST,
        POST
    ]
    os.write(filehandle, bytes(wrtbuf))
    termios.tcdrain(filehandle)
    ok, data = read_uart(7)  # id cmd pos pos pos err err
    if (not ok):  # or wrtbuf[0]!=CMD_GET_ERROR or wrtbuf[1]!=dest) :
        return -1, -1
    pos = (data[2] << 16) | (data[3] << 8) | data[4]
    # sign extend from 24 to 32 bit
    # python is very bad at typing. This does not work:
    #if pos & 0x00800000 : pos = int(pos | 0xFF000000)
    if pos & 0x00800000:
        pos = int((pos | 0xFF000000) - 0x100000000)
    err = (data[5] << 8) | data[6]
    return pos, err
예제 #30
0
def real_main(args: List[str]) -> None:
    msg = 'Show an error message'
    cli_opts, items = parse_args(args[1:],
                                 OPTIONS,
                                 '',
                                 msg,
                                 'hints',
                                 result_class=ErrorCLIOptions)
    data = json.loads(sys.stdin.buffer.read())
    error_message = data['msg']
    if cli_opts.title:
        print(styled(cli_opts.title, fg_intense=True, fg='red', bold=True))
        print()
    print(error_message, flush=True)
    if data.get('tb'):
        import select
        from kittens.tui.operations import init_state, set_cursor_visible
        fd, original_termios = open_tty()
        msg = '\n\r\x1b[1;32mPress e to see detailed traceback or any other key to exit\x1b[m'
        write_all(fd, msg)
        write_all(
            fd,
            init_state(alternate_screen=False, kitty_keyboard_mode=False) +
            set_cursor_visible(False))
        with no_echo(fd):
            termios.tcdrain(fd)
            while True:
                rd = select.select([fd], [], [])[0]
                if not rd:
                    break
                q = os.read(fd, 1)
                if q in b'eE':
                    break
                return
    if data.get('tb'):
        tb = data['tb']
        for ln in tb.splitlines():
            print('\r\n', ln, sep='', end='')
        print(flush=True)
    hold_till_enter()
예제 #31
0
    def _execute(self, code: str, timeout: float = 5) -> None:
        """Run the given Python code.

        To make sure the code returns, we do the following:

        1. Send the code to stdin, followed by \n
        2. Send a separate line: print('_ok')\n
        3. Read back the '_ok\n' on stdout

        This strategy lets us write _blocks_ of code (since the un-indented
        print() comes after, Python knows the block is closed). But if the code
        outputs any messages, that's an error.

        Keyword arguments:
        timeout -- Number of seconds to wait for _ok before throwing
        """
        self._ensure_empty_stdout_and_stderr()

        message = f"{code}\nprint('_ok')\n".encode('utf-8')
        os.write(self.pty_master, message)
        termios.tcdrain(self.pty_master)
        r, _, _ = select.select([self.shell.stdout, self.shell.stderr], [], [],
                                timeout)
        b = b''
        if r == [self.shell.stdout]:
            b = r[0].read(4)
            if b == b"_ok\n":
                return  # we're done!
            raise RuntimeError(
                f'Expected b"_ok\\n"; got: {b}\nCode was:\n{code}')
        else:
            if not r:
                raise RuntimeError(f'Timeout running code:\n{code}')
            else:
                raise RuntimeError('\n'.join([
                    'Python wrote to stderr while executing code:',
                    code,
                    'STDERR:',
                    str(r[0].read()),
                ]))
예제 #32
0
 def _restore_attrs(self):
     try:
         # Run drain first to ensure that we get the most recent state.
         termios.tcdrain(self.fd)
     except Exception as e:
         warning_message(self.context, "error while draining:", e)
     new_attrs = termios.tcgetattr(self.fd)
     if new_attrs == self.attrs:
         return
     warning_message(self.context, "TTY flags for", self.fd.name, "changed, resetting them")
     print("Previous state", self.attrs)
     print("New state", new_attrs)
     try:
         termios.tcsetattr(self.fd, termios.TCSADRAIN, self.attrs)
         termios.tcdrain(self.fd)
     except Exception as e:
         warning_message(self.context, "error while restoring TTY flags:", e)
     new_attrs = termios.tcgetattr(self.fd)
     if new_attrs != self.attrs:
         warning_message(self.context, "failed to restore TTY flags for", self.fd.name)
         print("Previous state", self.attrs)
         print("New state", new_attrs)
예제 #33
0
def hold_till_enter() -> None:
    import select
    import termios

    from kittens.tui.operations import init_state, set_cursor_visible
    fd, original_termios = open_tty()
    msg = '\n\r\x1b[1;32mPress Enter or Esc to exit\x1b[m'
    write_all(fd, msg)
    write_all(
        fd,
        init_state(alternate_screen=False, kitty_keyboard_mode=False) +
        set_cursor_visible(False))
    with no_echo(fd):
        termios.tcdrain(fd)
        while True:
            rd = select.select([fd], [], [])[0]
            if not rd:
                break
            q = os.read(fd, 1)
            if q in b'\n\r\x1b':
                break
            if q in b'\x03\x04':
                write_all(fd, msg)
예제 #34
0
 def drain(self):
     "Wait for the associated device to drain (e.g. before closing)."
     termios.tcdrain(self.fd)
예제 #35
0
 def runs_tcall():
     termios.tcsendbreak(2, 0)
     termios.tcdrain(2)
     termios.tcflush(2, termios.TCIOFLUSH)
     termios.tcflow(2, termios.TCOON)
예제 #36
0
 def drainOutput(self):
     """internal - not portable!"""
     if not self._isOpen: raise portNotOpenError
     termios.tcdrain(self.fd)
예제 #37
0
 def drainOutput(self):
   termios.tcdrain(self.fd)
예제 #38
0
def _execute_internal_capture_signals(run_command, signal_handler, stdout, stderr):

    # Listener used to know if SIGCONT has been received
    listener = SignalListener()
    if signal_handler:
        signal_handler.add_listener(signal.SIGCONT, listener)

    # save original tty setting if a tty exists
    old_tty_attr = None
    if is_interactive():
        old_tty_attr = termios.tcgetattr(sys.stdin)

        # get the current settings se we can modify them
        newattr = termios.tcgetattr(sys.stdin)

        # set the terminal to uncanonical mode and turn off
        # input echo.
        newattr[3] &= ~termios.ICANON & ~termios.ECHO

        # set our new attributes
        termios.tcsetattr(sys.stdin, termios.TCSADRAIN, newattr)

    master_fd = None
    master_stderr_fd = None
    try:
        # Open pseudo-terminals to interact with subprocess. Need one for stdout and one for stderr
        master_fd, slave_fd = pty.openpty()
        master_stderr_fd, slave_stderr_fd = pty.openpty()

        # Use os.setsid() make it run in a new process group, or bash job control will not be enabled
        # This is needed because docker needs to run in the foreground but if it runs in the foreground
        # of the current process group it will automatically catch all signals.
        p = Popen(
            run_command,
            preexec_fn=os.setsid,
            stdin=slave_fd,
            stdout=slave_fd,
            stderr=slave_stderr_fd,
            universal_newlines=True)

        data_in_last_loop = True  # True to start with to always enter loop
        while p.poll() is None or data_in_last_loop:
            if in_foreground() and is_interactive():
                r, w, e = select.select([sys.stdin, master_fd, master_stderr_fd], [], [], 0.2)
            else:
                r, w, e = select.select([master_fd, master_stderr_fd], [], [], 0.2)
            data_in_last_loop = bool(r)

            if listener.occurred:
                # After SIGCONT the select says that there is something  to read from stdin
                # but for some reason there isn't which makes os.read block until next input
                # which might be never
                listener.occurred = False

                if is_interactive() and in_foreground():
                    # drain stdin only if the process is in the foreground otherwise
                    # we don't have access to stdin and this will hang
                    termios.tcdrain(sys.stdin)

                # Similar to stdin the select says that there are things to read
                # but reading hangs. This could lead to data loss if there are things
                # to read from the subprocess stdout/stderr but no idea how to handle that
                termios.tcdrain(master_fd)
                termios.tcdrain(master_stderr_fd)

            else:
                if sys.stdin in r:
                    # Read from stdin and write to subprocess stdin
                    d = os.read(sys.stdin.fileno(), 10240)
                    os.write(master_fd, d)

                if master_fd in r:
                    # Read from subprocess stdout and write to stdout
                    o = os.read(master_fd, 10240)
                    if o:
                        try:
                            # If stderr is a StringIO this will fail
                            os.write(stdout.fileno(), o)
                        except Exception:
                            stdout.write(o.decode('utf-8', 'ignore'))

                if master_stderr_fd in r:
                    # Read from subprocess stderr and write to stderr
                    o = os.read(master_stderr_fd, 10240)
                    if o:
                        try:
                            # If stderr is a StringIO this will fail
                            os.write(stderr.fileno(), o)
                        except Exception:
                            stderr.write(o.decode('utf-8', 'ignore'))

        return_value = p.wait()

        logger.debug(
            'Docker run completed with return value: {return_value}'.format(
                return_value=return_value))

    finally:
        if master_fd:
            os.close(master_fd)

        if master_stderr_fd:
            os.close(master_stderr_fd)

        if old_tty_attr is not None and in_foreground() and is_interactive():
            # Reset stdin if in foreground
            termios.tcsetattr(sys.stdin, termios.TCSADRAIN, old_tty_attr)

        if signal_handler:
            signal_handler.remove_listener(signal.SIGCONT, listener)

    return return_value
예제 #39
0
def write_test(rxThread, read_timeout, ser, baud, data_to_send, write_size, write_delay, warm_up, cool_down):
	try:
		if not ser.isOpen():
			ser.open()
		# set bauderate
		ser.setBaudrate(baud)
		ser.setRTS(False)
		ser.setDTR(True)
		if USE_TCDRAIN:
			iflag, oflag, cflag, lflag, ispeed, ospeed, cc = termios.tcgetattr(ser.fd)
			iflag |= (TERMIOS.IGNBRK | TERMIOS.IGNPAR)
			termios.tcsetattr(ser.fd, TERMIOS.TCSANOW, [iflag, oflag, cflag, lflag, ispeed, ospeed, cc])
	except serial.SerialException:
		print ('serial.SerialException : Failure to change the baudrate to {0}.'.format(baud))
		raise BaseException
	# verify port is still open
	if not ser.isOpen():
		print ('Port no longer open')
		raise BaseException
	# set RTS and warm_up
	print ('Start Transmitting')
	ser.setRTS(True)
	time.sleep(warm_up)
	# start sending
	data = data_to_send[:]
	while len(data) is not 0:
		write_len = min(len(data), write_size)
		ser.write(data[:write_len])
		data = data[write_len:]
		time.sleep(write_delay)
	# set cool_down and RTS
	if USE_TCDRAIN:
		termios.tcdrain(ser.fd)
	time.sleep(cool_down)
	# set RTS to off
	ser.setRTS(False)
	print ('Finished Transmitting')
	# still recieving
	rxThread.running_lock.acquire()
	if not rxThread.running:
		rxThread.running_lock.release()
		print ('Recieve thread prematurly terminated')
		raise BaseException
	rxThread.running_lock.release()
	# examin and display recieved data
	read_start_time = time.time()
	read_data = ''
	while ((len(read_data) < len(data_to_send))  and ((time.time() - read_start_time) < read_timeout)):
		try:
			(packet, packet_time) = rxThread.read_queue.get(True, read_timeout)
			print ('recieved {len} bytes within {time:1.4} seconds'.format(len=len(packet), time=packet_time))
			read_data += packet
		except Queue.Empty:
			pass
	if (len(read_data) is not len(data_to_send)):
		print ('The TX and RX data does not match - Length is different')
	if (read_data == data_to_send):
		print ('Recieved all the transmitted data !!!')
		#print_data_diff(read_data, data_to_send)
	else:
		print ('The TX and RX data does not match - different data')
		print_data_diff(read_data, data_to_send)
예제 #40
0
 def finalizer():
     termios.tcdrain(tty_fileno)
예제 #41
0
 def drainOutput(self):
     """internal - not portable!"""
     if not self._isOpen: raise portNotOpenError
     termios.tcdrain(self.fd)
예제 #42
0
def tcdrain(space, fd):
    try:
        termios.tcdrain(fd)
    except termios.error, e:
        e.errno = e.args[0]
        raise convert_error(space, e)
예제 #43
0
파일: gertbot.py 프로젝트: oatmeal3000/qupy
def get_io_setup(brd) :
   #GB_CHECK(brd>=0 && brd<=3,  "get_io_status illegal board\n");
   id = brd<<2
   tx = [0]*20
   tx[0] = PRE
   tx[1] = CMD_IO_STATUS
   tx[2] = id
   for i in range(3,19) : 
      tx[i] = POST;
   os.write(filehandle,bytes(tx))
   termios.tcdrain(filehandle)
  
   # Read input/output status
   # return is:
   #  - ID, CMD            (2 bytes)  0, 1
   #  - adc_enable     3-0 (1 byte)   2
   #  - dac_enable     1-0 (1 byte)   3
   #  - inputs pins   23-0 (3 bytes)  4, 5, 6
   #  - output pins   23-0 (3 bytes)  7, 8, 9
   #  - output status 23-0 (3 bytes) 10,11,12
   #  - open drain status (1 unsigned char)   13
   #  - unused (2 bytes)             14,15
   # Total 16 bytes
   ok , rec_data = read_uart(16)
   if (not ok) : # or rec_data[0]!=CMD_IO_STATUS or rec_data[1]!=dest) :
      status = []
      return status

   # EXT
   for i in range(0,8) : 
      if (rec_data[6] & (1<<i)) : 
         pin_mode[brd][i^1] = PIN_INPUT
      else : 
         if (rec_data[9] & (1<<i)) : 
            pin_mode[brd][i^1] = PIN_OUTPUT
         else : # not input or output must be endstop
            pin_mode[brd][i^1] = PIN_ENDSTOP
   
   # Spares
   for i in range(0,2) : 
      if (rec_data[5] & (1<<i)) :
         pin_mode[brd][i^1+8] = PIN_INPUT
      else :
         pin_mode[brd][i^1+8] = PIN_OUTPUT
      # to do : I2C mode 
   
   # ADCs
   for i in range(0,4) : 
      if (rec_data[2] & (1<<i)) :
        pin_mode[brd][i^1+12] = PIN_ADC
      else :
         if (rec_data[5] & (0x04<<i)) :
            pin_mode[brd][i^1+12] = PIN_INPUT
         else :
            pin_mode[brd][i^1+12] = PIN_OUTPUT
   
   # DACs
   if (rec_data[3] & (0x02)) : # DAC1
      pin_mode[brd][17] = PIN_DAC
   else :
      if (rec_data[5] & 0x40) :
         pin_mode[brd][17] = PIN_INPUT
      else :
         pin_mode[brd][17] = PIN_OUTPUT
   
   if (rec_data[3] & (0x01)) : # DAC0
      pin_mode[brd][19] = PIN_DAC
   else :
      if (rec_data[5] & 0x80) :
         pin_mode[brd][19] = PIN_INPUT
      else :
         pin_mode[brd][19] = PIN_OUTPUT
         
   # gather up all pins and return in list 
   status = [0]*20
   for i in range(0,20) :
      status[i] = pin_mode[brd][i]
       
   return status
예제 #44
0
 def finalizer():
   termios.tcdrain(tty_fileno)
예제 #45
0
파일: rcserial.py 프로젝트: amlinux/rcrobot
 def flush(self):
     termios.tcdrain(self.fd)
예제 #46
0
 def drain(self):
     "Wait for the associated device to drain (e.g. before closing)."
     termios.tcdrain(self.fd)
예제 #47
0
 def send_command(self, command):
     logging.info("--> %s" % command)
     out = "%s\r\n" % command
     os.write(self.file, out.encode("UTF-8"))
     termios.tcdrain(self.file)
예제 #48
0
 def drainOutput(self):
     if not self.fd: raise portNotOpenError
     termios.tcdrain(self.fd)
예제 #49
0
  print(curs.fetchone())
  conn.close()

def test_icmp():
  return subprocess.call(["/bin/ping", "-c1", "-W"+str(ICMP_TIMEOUT), ICMP_IP])

def send_sysrq(key):
  try:
    fd = os.open(TTY_PATH, os.O_RDWR | os.O_SYNC) # no buffering
  except Exception, e:
    log("Cannot open " + TTY_PATH + ": " + e.__str__())
  else:
    try:
      termios.tcsendbreak(fd, 0)
      os.write(fd, key)
      termios.tcdrain(fd)
    except Exception, e:
      log("We could not send the sysrq! " + e.__str__())
    else:
      log("sysrq sent!")
    os.close(fd)

def server_down():
  if violent:
    send_sysrq(SYSRQ_KEY)
  else:
    log("We would sysrq-c if we were violent!")

if __name__ == '__main__':
  if len(sys.argv) < 2:
    print("Please use parameter within:\n - " + VIOLENT_ARG + " to send a sysrq on timeouts\n - test-sysrq to send a sysrq-t\n - anything else for simulation")
예제 #50
0
파일: ptyhelper.py 프로젝트: yanicky/d-rats
 def write(self, str):
     r = safe_write(self.fd, str, self.timeout)
     termios.tcdrain(self.fd)
     return r
예제 #51
0
	def send_command(self, command):
		dprint("-->", command)
		os.write(self.file, "%s\r\n" % command)
		termios.tcdrain(self.file)
예제 #52
0
def _poll_process(parent_pty, epoll, p, cmd, decoder, state):
    """Polls the process and captures / forwards input and output."""

    terminated = p.poll() is not None
    if terminated:
        termios.tcdrain(parent_pty)
        # We're no longer interested in write events and only want to consume any
        # remaining output from the terminated process. Continuing to watch write
        # events may cause early termination of the loop if no output was
        # available but the pty was ready for writing.
        epoll.modify(parent_pty,
                     (select.EPOLLIN | select.EPOLLHUP | select.EPOLLERR))

    output_available = False

    events = epoll.poll()
    input_events = []
    for _, event in events:
        if event & select.EPOLLIN:
            output_available = True
            raw_contents = os.read(parent_pty, _PTY_READ_MAX_BYTES_FOR_TEST)
            decoded_contents = decoder.decode(raw_contents)

            sys.stdout.write(decoded_contents)
            state.process_output.write(decoded_contents)

        if event & select.EPOLLOUT:
            # Queue polling for inputs behind processing output events.
            input_events.append(event)

        # PTY was disconnected or encountered a connection error. In either case,
        # no new output should be made available.
        if (event & select.EPOLLHUP) or (event & select.EPOLLERR):
            state.is_pty_still_connected = False

    for event in input_events:
        # Check to see if there is any input on the stdin socket.
        # pylint: disable=protected-access
        input_line = _message._read_stdin_message()
        # pylint: enable=protected-access
        if input_line is not None:
            # If a very large input or sequence of inputs is available, it's
            # possible that the PTY buffer could be filled and this write call
            # would block. To work around this, non-blocking writes and keeping
            # a list of to-be-written inputs could be used. Empirically, the
            # buffer limit is ~12K, which shouldn't be a problem in most
            # scenarios. As such, optimizing for simplicity.
            input_bytes = bytes(input_line.encode(_ENCODING))
            os.write(parent_pty, input_bytes)

    # Once the process is terminated, there still may be output to be read from
    # the PTY. Wait until the PTY has been disconnected and no more data is
    # available for read. Simply waiting for disconnect may be insufficient if
    # there is more data made available on the PTY than we consume in a single
    # read call.
    if terminated and not state.is_pty_still_connected and not output_available:
        sys.stdout.flush()
        command_output = state.process_output.getvalue()
        return ShellResult(cmd, p.returncode, command_output)

    if not output_available:
        # The PTY is almost continuously available for reading input to provide
        # to the underlying subprocess. This means that the polling loop could
        # effectively become a tight loop and use a large amount of CPU. Add a
        # slight delay to give resources back to the system while monitoring the
        # process.
        # Skip this delay if we read output in the previous loop so that a partial
        # read doesn't unnecessarily sleep before reading more output.
        # TODO(b/115527726): Rather than sleep, poll for incoming messages from
        # the frontend in the same poll as for the output.
        time.sleep(0.1)
예제 #53
0
 def runs_tcall():
     termios.tcsendbreak(2, 0)
     termios.tcdrain(2)
     termios.tcflush(2, termios.TCIOFLUSH)
     termios.tcflow(2, termios.TCOON)
예제 #54
0
 def drainOutput(self):
     """internal - not portable!"""
     if self.fd is None: raise portNotOpenError
     termios.tcdrain(self.fd)
예제 #55
0
def tcdrain(space, w_fd):
    fd = space.c_filedescriptor_w(w_fd)
    try:
        termios.tcdrain(fd)
    except OSError, e:
        raise convert_error(space, e)
예제 #56
0
 def drainOutput(self):
     """internal - not portable!"""
     if self.fd is None: raise portNotOpenError
     termios.tcdrain(self.fd)
예제 #57
0
def tcdrain(space, fd):
    try:
        termios.tcdrain(fd)
    except OSError, e:
        raise convert_error(space, e)