示例#1
0
 def write(self, data):
     """Output the given byte string over the serial port."""
     if not self.is_open:
         raise portNotOpenError
     d = to_bytes(data)
     tx_len = length = len(d)
     timeout = Timeout(self._write_timeout)
     while tx_len > 0:
         try:
             n = os.write(self.fd, d)
             if timeout.is_non_blocking:
                 # Zero timeout indicates non-blocking - simply return the
                 # number of bytes of data actually written
                 return n
             elif not timeout.is_infinite:
                 # when timeout is set, use select to wait for being ready
                 # with the time left as timeout
                 if timeout.expired():
                     raise writeTimeoutError
                 abort, ready, _ = select.select([self.pipe_abort_write_r],
                                                 [self.fd], [],
                                                 timeout.time_left())
                 if abort:
                     os.read(self.pipe_abort_write_r, 1000)
                     break
                 if not ready:
                     raise writeTimeoutError
             else:
                 assert timeout.time_left() is None
                 # wait for write operation
                 abort, ready, _ = select.select([self.pipe_abort_write_r],
                                                 [self.fd], [], None)
                 if abort:
                     os.read(self.pipe_abort_write_r, 1)
                     break
                 if not ready:
                     raise SerialException('write failed (select)')
             d = d[n:]
             tx_len -= n
         except SerialException:
             raise
         except OSError as e:
             # this is for Python 3.x where select.error is a subclass of
             # OSError ignore BlockingIOErrors and EINTR. other errors are shown
             # https://www.python.org/dev/peps/pep-0475.
             if e.errno not in (errno.EAGAIN, errno.EALREADY,
                                errno.EWOULDBLOCK, errno.EINPROGRESS,
                                errno.EINTR):
                 raise SerialException('write failed: {}'.format(e))
         except select.error as e:
             # this is for Python 2.x
             # ignore BlockingIOErrors and EINTR. all errors are shown
             # see also http://www.python.org/dev/peps/pep-3151/#select
             if e[0] not in (errno.EAGAIN, errno.EALREADY,
                             errno.EWOULDBLOCK, errno.EINPROGRESS,
                             errno.EINTR):
                 raise SerialException('write failed: {}'.format(e))
         if not timeout.is_non_blocking and timeout.expired():
             raise writeTimeoutError
     return length - len(d)
    def write(self, data):
        """\
        Output the given byte string over the serial port. Can block if the
        connection is blocked. May raise SerialException if the connection is
        closed.
        """
        if not self.is_open:
            raise portNotOpenError

        d = to_bytes(data)
        tx_len = length = len(d)
        timeout = Timeout(self._write_timeout)
        while tx_len > 0:
            try:
                n = self._socket.send(d)
                if timeout.is_non_blocking:
                    # Zero timeout indicates non-blocking - simply return the
                    # number of bytes of data actually written
                    return n
                elif not timeout.is_infinite:
                    # when timeout is set, use select to wait for being ready
                    # with the time left as timeout
                    if timeout.expired():
                        raise writeTimeoutError
                    _, ready, _ = select.select([], [self._socket], [], timeout.time_left())
                    if not ready:
                        raise writeTimeoutError
                else:
                    assert timeout.time_left() is None
                    # wait for write operation
                    _, ready, _ = select.select([], [self._socket], [], None)
                    if not ready:
                        raise SerialException('write failed (select)')
                d = d[n:]
                tx_len -= n
            except SerialException:
                raise
            except OSError as e:
                # this is for Python 3.x where select.error is a subclass of
                # OSError ignore BlockingIOErrors and EINTR. other errors are shown
                # https://www.python.org/dev/peps/pep-0475.
                if e.errno not in (errno.EAGAIN, errno.EALREADY, errno.EWOULDBLOCK, errno.EINPROGRESS, errno.EINTR):
                    raise SerialException('write failed: {}'.format(e))
            except select.error as e:
                # this is for Python 2.x
                # ignore BlockingIOErrors and EINTR. all errors are shown
                # see also http://www.python.org/dev/peps/pep-3151/#select
                if e[0] not in (errno.EAGAIN, errno.EALREADY, errno.EWOULDBLOCK, errno.EINPROGRESS, errno.EINTR):
                    raise SerialException('write failed: {}'.format(e))
            if not timeout.is_non_blocking and timeout.expired():
                raise writeTimeoutError
        return length - len(d)
 def write(self, data):
     """Output the given byte string over the serial port."""
     if not self.is_open:
         raise portNotOpenError
     d = to_bytes(data)
     tx_len = length = len(d)
     timeout = Timeout(self._write_timeout)
     while tx_len > 0:
         try:
             n = os.write(self.fd, d)
             if timeout.is_non_blocking:
                 # Zero timeout indicates non-blocking - simply return the
                 # number of bytes of data actually written
                 return n
             elif not timeout.is_infinite:
                 # when timeout is set, use select to wait for being ready
                 # with the time left as timeout
                 if timeout.expired():
                     raise writeTimeoutError
                 abort, ready, _ = select.select([self.pipe_abort_write_r],
                                                 [self.fd], [],
                                                 timeout.time_left())
                 if abort:
                     os.read(self.pipe_abort_write_r, 1000)
                     break
                 if not ready:
                     raise writeTimeoutError
             else:
                 assert timeout.time_left() is None
                 # wait for write operation
                 abort, ready, _ = select.select([self.pipe_abort_write_r],
                                                 [self.fd], [], None)
                 if abort:
                     os.read(self.pipe_abort_write_r, 1)
                     break
                 if not ready:
                     raise SerialException('write failed (select)')
             d = d[n:]
             tx_len -= n
         except SerialException:
             raise
         except OSError as v:
             if v.errno != errno.EAGAIN:
                 raise SerialException('write failed: {}'.format(v))
             # still calculate and check timeout
             if timeout.expired():
                 raise writeTimeoutError
     return length - len(d)
示例#4
0
 def read(self, size=1):
     """\
     Read size bytes from the serial port. If a timeout is set it may
     return less characters as requested. With no timeout it will block
     until the requested number of bytes is read.
     """
     if not self.is_open:
         raise PortNotOpenError()
     read = bytearray()
     timeout = Timeout(self._timeout)
     poll = select.poll()
     poll.register(self.fd, select.POLLIN | select.POLLERR | select.POLLHUP | select.POLLNVAL)
     poll.register(self.pipe_abort_read_r, select.POLLIN | select.POLLERR | select.POLLHUP | select.POLLNVAL)
     if size > 0:
         while len(read) < size:
             # print "\tread(): size",size, "have", len(read)    #debug
             # wait until device becomes ready to read (or something fails)
             for fd, event in poll.poll(None if timeout.is_infinite else (timeout.time_left() * 1000)):
                 if fd == self.pipe_abort_read_r:
                     break
                 if event & (select.POLLERR | select.POLLHUP | select.POLLNVAL):
                     raise SerialException('device reports error (poll)')
                 #  we don't care if it is select.POLLIN or timeout, that's
                 #  handled below
             if fd == self.pipe_abort_read_r:
                 os.read(self.pipe_abort_read_r, 1000)
                 break
             buf = os.read(self.fd, size - len(read))
             read.extend(buf)
             if timeout.expired() \
                     or (self._inter_byte_timeout is not None and self._inter_byte_timeout > 0) and not buf:
                 break   # early abort on timeout
     return bytes(read)
示例#5
0
    def read(self, size=1):
        """\
        Read size bytes from the serial port. If a timeout is set it may
        return less characters as requested. With no timeout it will block
        until the requested number of bytes is read.
        """
        if not self.is_open:
            raise PortNotOpenError()
        read = bytearray()
        timeout = Timeout(self._timeout)
        while len(read) < size:
            try:
                ready, _, _ = select.select([self.fd, self.pipe_abort_read_r],
                                            [], [], timeout.time_left())
                if self.pipe_abort_read_r in ready:
                    os.read(self.pipe_abort_read_r, 1000)
                    break
                # If select was used with a timeout, and the timeout occurs, it
                # returns with empty lists -> thus abort read operation.
                # For timeout == 0 (non-blocking operation) also abort when
                # there is nothing to read.
                if not ready:
                    break  # timeout
                buf = os.read(self.fd, size - len(read))
            except OSError as e:
                # this is for Python 3.x where select.error is a subclass of
                # OSError ignore BlockingIOErrors and EINTR. other errors are shown
                # https://www.python.org/dev/peps/pep-0475.
                if e.errno not in (errno.EAGAIN, errno.EALREADY,
                                   errno.EWOULDBLOCK, errno.EINPROGRESS,
                                   errno.EINTR):
                    raise SerialException('read failed: {}'.format(e))
            except select.error as e:
                # this is for Python 2.x
                # ignore BlockingIOErrors and EINTR. all errors are shown
                # see also http://www.python.org/dev/peps/pep-3151/#select
                if e[0] not in (errno.EAGAIN, errno.EALREADY,
                                errno.EWOULDBLOCK, errno.EINPROGRESS,
                                errno.EINTR):
                    raise SerialException('read failed: {}'.format(e))
            else:
                # read should always return some data as select reported it was
                # ready to read when we get to this point.
                if not buf:
                    # Disconnected devices, at least on Linux, show the
                    # behavior that they are always ready to read immediately
                    # but reading returns nothing.
                    raise SerialException(
                        'device reports readiness to read but returned no data '
                        '(device disconnected or multiple access on port?)')
                read.extend(buf)

            if timeout.expired():
                break
            elif self._inter_byte_timeout is not None and self._inter_byte_timeout > 0:
                #atleast one char received --> overwrite timeout by setting it to inter_byte_timeout
                timeout = Timeout(self._inter_byte_timeout)

        return bytes(read)
 def read(self, size=1):
     """\
     Read size bytes from the serial port. If a timeout is set it may
     return less characters as requested. With no timeout it will block
     until the requested number of bytes is read.
     """
     if not self.is_open:
         raise PortNotOpenError()
     read = bytearray()
     timeout = Timeout(self._timeout)
     while len(read) < size:
         try:
             ready, _, _ = select.select([self._socket], [], [],
                                         timeout.time_left())
             # If select was used with a timeout, and the timeout occurs, it
             # returns with empty lists -> thus abort read operation.
             # For timeout == 0 (non-blocking operation) also abort when
             # there is nothing to read.
             if not ready:
                 break  # timeout
             buf = self._socket.recv(size - len(read))
             # read should always return some data as select reported it was
             # ready to read when we get to this point, unless it is EOF
             if not buf:
                 raise SerialException('socket disconnected')
             read.extend(buf)
         except OSError as e:
             # this is for Python 3.x where select.error is a subclass of
             # OSError ignore BlockingIOErrors and EINTR. other errors are shown
             # https://www.python.org/dev/peps/pep-0475.
             if e.errno not in (errno.EAGAIN, errno.EALREADY,
                                errno.EWOULDBLOCK, errno.EINPROGRESS,
                                errno.EINTR):
                 raise SerialException('read failed: {}'.format(e))
         except (select.error, socket.error) as e:
             # this is for Python 2.x
             # ignore BlockingIOErrors and EINTR. all errors are shown
             # see also http://www.python.org/dev/peps/pep-3151/#select
             if e[0] not in (errno.EAGAIN, errno.EALREADY,
                             errno.EWOULDBLOCK, errno.EINPROGRESS,
                             errno.EINTR):
                 raise SerialException('read failed: {}'.format(e))
         if timeout.expired():
             break
     return bytes(read)
示例#7
0
 def write(self, data):
     """Output the given byte string over the serial port."""
     if not self.is_open:
         raise portNotOpenError
     d = to_bytes(data)
     tx_len = len(d)
     timeout = Timeout(self._write_timeout)
     while tx_len > 0:
         try:
             n = os.write(self.fd, d)
             if timeout.is_non_blocking:
                 # Zero timeout indicates non-blocking - simply return the
                 # number of bytes of data actually written
                 return n
             elif not timeout.is_infinite:
                 # when timeout is set, use select to wait for being ready
                 # with the time left as timeout
                 if timeout.expired():
                     raise writeTimeoutError
                 abort, ready, _ = select.select([self.pipe_abort_write_r], [self.fd], [], timeout.time_left())
                 if abort:
                     os.read(self.pipe_abort_write_r, 1000)
                     break
                 if not ready:
                     raise writeTimeoutError
             else:
                 assert timeout.time_left() is None
                 # wait for write operation
                 abort, ready, _ = select.select([self.pipe_abort_write_r], [self.fd], [], None)
                 if abort:
                     os.read(self.pipe_abort_write_r, 1)
                     break
                 if not ready:
                     raise SerialException('write failed (select)')
             d = d[n:]
             tx_len -= n
         except SerialException:
             raise
         except OSError as v:
             if v.errno != errno.EAGAIN:
                 raise SerialException('write failed: {}'.format(v))
             # still calculate and check timeout
             if timeout.expired():
                 raise writeTimeoutError
     return len(data)
示例#8
0
    def read(self, size=1):
        if not self.is_open:
            raise portNotOpenError

        data = bytearray()
        try:
            timeout = Timeout(self._timeout)
            while len(data) < size:
                if self._thread is None:
                    raise SerialException(
                        'connection failed (reader thread died)')
                buf = self._read_buffer.get(True, timeout.time_left())
                if buf is None:
                    return bytes(data)
                data += buf
                if timeout.expired():
                    break
        except Queue.Empty:  # -> timeout
            pass
        return bytes(data)
 def read(self, size=1):
     """\
     Read size bytes from the serial port. If a timeout is set it may
     return less characters as requested. With no timeout it will block
     until the requested number of bytes is read.
     """
     if not self.is_open:
         raise portNotOpenError
     read = bytearray()
     timeout = Timeout(self._timeout)
     while len(read) < size:
         try:
             ready, _, _ = select.select([self._socket], [], [], timeout.time_left())
             # If select was used with a timeout, and the timeout occurs, it
             # returns with empty lists -> thus abort read operation.
             # For timeout == 0 (non-blocking operation) also abort when
             # there is nothing to read.
             if not ready:
                 break   # timeout
             buf = self._socket.recv(size - len(read))
             # read should always return some data as select reported it was
             # ready to read when we get to this point, unless it is EOF
             if not buf:
                 raise SerialException('socket disconnected')
             read.extend(buf)
         except OSError as e:
             # this is for Python 3.x where select.error is a subclass of
             # OSError ignore BlockingIOErrors and EINTR. other errors are shown
             # https://www.python.org/dev/peps/pep-0475.
             if e.errno not in (errno.EAGAIN, errno.EALREADY, errno.EWOULDBLOCK, errno.EINPROGRESS, errno.EINTR):
                 raise SerialException('read failed: {}'.format(e))
         except (select.error, socket.error) as e:
             # this is for Python 2.x
             # ignore BlockingIOErrors and EINTR. all errors are shown
             # see also http://www.python.org/dev/peps/pep-3151/#select
             if e[0] not in (errno.EAGAIN, errno.EALREADY, errno.EWOULDBLOCK, errno.EINPROGRESS, errno.EINTR):
                 raise SerialException('read failed: {}'.format(e))
         if timeout.expired():
             break
     return bytes(read)
示例#10
0
 def read(self, size=1):
     """\
     Read size bytes from the serial port. If a timeout is set it may
     return less characters as requested. With no timeout it will block
     until the requested number of bytes is read.
     """
     if not self.is_open:
         raise portNotOpenError
     read = bytearray()
     timeout = Timeout(self._timeout)
     while len(read) < size:
         try:
             ready, _, _ = select.select([self.fd, self.pipe_abort_read_r], [], [], timeout.time_left())
             if self.pipe_abort_read_r in ready:
                 os.read(self.pipe_abort_read_r, 1000)
                 break
             # If select was used with a timeout, and the timeout occurs, it
             # returns with empty lists -> thus abort read operation.
             # For timeout == 0 (non-blocking operation) also abort when
             # there is nothing to read.
             if not ready:
                 break   # timeout
             buf = os.read(self.fd, size - len(read))
             # read should always return some data as select reported it was
             # ready to read when we get to this point.
             if not buf:
                 # Disconnected devices, at least on Linux, show the
                 # behavior that they are always ready to read immediately
                 # but reading returns nothing.
                 raise SerialException(
                     'device reports readiness to read but returned no data '
                     '(device disconnected or multiple access on port?)')
             read.extend(buf)
         except OSError as e:
             # this is for Python 3.x where select.error is a subclass of
             # OSError ignore EAGAIN errors. all other errors are shown
             if e.errno != errno.EAGAIN and e.errno != errno.EINTR:
                 raise SerialException('read failed: {}'.format(e))
         except select.error as e:
             # this is for Python 2.x
             # ignore EAGAIN errors. all other errors are shown
             # see also http://www.python.org/dev/peps/pep-3151/#select
             if e[0] != errno.EAGAIN:
                 raise SerialException('read failed: {}'.format(e))
         if timeout.expired():
             break
     return bytes(read)
示例#11
0
 def read(self, size=1):
     """\
     Read size bytes from the serial port. If a timeout is set it may
     return less characters as requested. With no timeout it will block
     until the requested number of bytes is read.
     """
     if not self.is_open:
         raise portNotOpenError
     read = bytearray()
     timeout = Timeout(self._timeout)
     while len(read) < size:
         try:
             ready, _, _ = select.select([self.fd, self.pipe_abort_read_r],
                                         [], [], timeout.time_left())
             if self.pipe_abort_read_r in ready:
                 os.read(self.pipe_abort_read_r, 1000)
                 break
             # If select was used with a timeout, and the timeout occurs, it
             # returns with empty lists -> thus abort read operation.
             # For timeout == 0 (non-blocking operation) also abort when
             # there is nothing to read.
             if not ready:
                 break  # timeout
             buf = os.read(self.fd, size - len(read))
             # read should always return some data as select reported it was
             # ready to read when we get to this point.
             if not buf:
                 # Disconnected devices, at least on Linux, show the
                 # behavior that they are always ready to read immediately
                 # but reading returns nothing.
                 raise SerialException(
                     'device reports readiness to read but returned no data '
                     '(device disconnected or multiple access on port?)')
             read.extend(buf)
         except OSError as e:
             # Devices connecting through a poor USB/Serial cable or an
             # underpowered USB hub can spontaneously disconnect from
             # the OS, and promptly reconnect.  If this happens, attempt
             # to reopen the device and continue the session.
             if e.errno == errno.ENXIO:
                 retryTimeout = Timeout(2)  # Allow for a short grace period
                 sys.stderr.write(
                     'pySerial WARNING: Serial device disappeared! '
                     '...Trying to reconnect...\n')
                 sys.stderr.write(
                     'pySerial WARNING: If this problem is chronic '
                     'replace your cable/powered USB HUB.\n')
                 sys.stderr.flush()
                 self.close()
                 while self.fd == None:
                     try:
                         self.open()
                     except OSError as e:
                         if e.errno != errno.ENOENT or retryTimeout.expired(
                         ):
                             raise SerialException(
                                 'Serial device gone: {}'.format(e))
                 break
             # this is for Python 3.x where select.error is a subclass of
             # OSError ignore BlockingIOErrors and EINTR. other errors are shown
             # https://www.python.org/dev/peps/pep-0475.
             elif e.errno not in (errno.EAGAIN, errno.EALREADY,
                                  errno.EWOULDBLOCK, errno.EINPROGRESS,
                                  errno.EINTR):
                 raise SerialException('read failed: {}'.format(e))
         except select.error as e:
             # this is for Python 2.x
             # ignore BlockingIOErrors and EINTR. all errors are shown
             # see also http://www.python.org/dev/peps/pep-3151/#select
             if e[0] not in (errno.EAGAIN, errno.EALREADY,
                             errno.EWOULDBLOCK, errno.EINPROGRESS,
                             errno.EINTR):
                 raise SerialException('read failed: {}'.format(e))
         if timeout.expired():
             break
     return bytes(read)