Пример #1
0
 def in_waiting(self):
     """Return the number of bytes currently in the input buffer."""
     flags = win32.DWORD()
     comstat = win32.COMSTAT()
     if not win32.ClearCommError(self._port_handle, ctypes.byref(flags), ctypes.byref(comstat)):
         raise SerialException('call to ClearCommError failed')
     return comstat.cbInQue
Пример #2
0
 def out_waiting(self):
     """Return how many bytes the in the outgoing buffer"""
     flags = win32.DWORD()
     comstat = win32.COMSTAT()
     if not win32.ClearCommError(self._port_handle, ctypes.byref(flags), ctypes.byref(comstat)):
         raise SerialException('call to ClearCommError failed')
     return comstat.cbOutQue
Пример #3
0
    def GetImage(self):
        ''' from the docs
        Command : 'I' grab JPEG compressed video frame
        Returns : '##IMJxs0s1s2s3....'     
            x = frame size in pixels: 1 = 80x64, 3 = 160x120, 5 = 320x240, 7 = 640x480, 9 = 1280x1024 
            s0s1s2s3=frame size in bytes (s0 * 256^0 + s1 * 256^1 + s2 * 256^2 + s3 * 256^3) 
            .... = full JPEG frame 

        Note that sometimes the 'I' command returns nothing if the robot camera is busy, 
        so the 'I' command should be called as many times as needed until a frame is returned
        '''

        data = self.SendCommand('I')

        #self.srvConn.timeout = .25
        #head = self.srvConn.read(10);
        if (len(data) < 10 or not (data[0:4] == '#IMJ')):
            self.flushInput()
            self.flushOutput()
            raise SerialException("Failed to read image header: '%s'" %
                                  data[:9])

        # process header info
        frameHead = unpack('<cHxx', data[4:9])

        #ImageResolution = frameHead[0]
        ImageSize = frameHead[1]

        if len(data) < ImageSize + 9:
            data += self.read()

        self._image = data[9:]
        return self._image
Пример #4
0
 def _connect_to_port(self, port=None):
     try:
         mag_deck = environ.get('OT_MAG_DECK_ID')
         self._connection = serial_communication.connect(
             device_name=mag_deck, port=port, baudrate=MAG_DECK_BAUDRATE)
     except SerialException:
         # if another process is using the port, pyserial raises an
         # exception that describes a "readiness to read" which is confusing
         error_msg = "Unable to access Serial port to Mag-Deck. This is"
         " because another process is currently using it, or"
         " the Serial port is disabled on this device (OS)"
         raise SerialException(error_msg)
     except TypeError:
         # This happens if there are no ttyMagDeck devices in /dev
         # For development use ENABLE_VIRTUAL_SMOOTHIE=true
         raise SerialException('No port specified')
Пример #5
0
    def SendCommand(self, Command):
        # clean up and send command
        self.flush()
        time.sleep(self._SendWait
                   )  # if this is excluded, you see your own transmits ?!
        self.write(Command)
        time.sleep(self._SendWait)

        # check for proper return value
        # We expect something like '#%s'%Command
        Retries = 0
        while True:
            r = self.read(4096)  # read everything until timeout
            if len(r) == 0:
                Retries += 1
                if Retries > self._MaxRetries:
                    raise TimeoutWarning("Timeout after %d retries" %
                                         (Retries - 1))
                else:
                    print >> sys.stderr, "Timeout #%d. Will retry." % Retries
                    continue
            if r[0] != '#':
                raise SerialException(
                    "Bad response received: Expected '%s' got '%s'" % ('#', r))

            # no probs? then continue
            break

        return r[1:]
Пример #6
0
    def connected(self):
        global i
        if (i == 0):
            self.connect_button.setText("Disconnect")
            print self.combobox1.currentText()
            print self.combobox2.currentText()
            if self.combobox1.currentText() != "":
                try:

                    self.sdr = serial.Serial(str(self.combobox1.currentText()),
                                             int(self.combobox2.currentText()),
                                             timeout=.1)
                    ## Creating csv object
                    time_stamp = time.strftime('%Y-%m-%d-%H-%M-%S')
                    time_stamp_file = str(time_stamp) + ".csv"
                    self.csvfile = open(time_stamp_file, "wb")
                except:
                    SerialException()
                    pass

            self.win2.showMaximized()
            self.win1.hide()
            i = i + 1
        elif (i == 1):
            self.connect_button.setText("Connect")
            self.sdr.close()
            i = 0
            print "Disconnected"
Пример #7
0
 def write(self, data):
     """Output the given byte string over the serial port."""
     if not self.is_open:
         raise portNotOpenError
     #~ if not isinstance(data, (bytes, bytearray)):
     #~ raise TypeError('expected %s or bytearray, got %s' % (bytes, type(data)))
     # convert data (needed in case of memoryview instance: Py 3.1 io lib), ctypes doesn't like memoryview
     data = to_bytes(data)
     if data:
         #~ win32event.ResetEvent(self._overlapped_write.hEvent)
         n = win32.DWORD()
         err = win32.WriteFile(self._port_handle, data, len(data),
                               ctypes.byref(n), self._overlapped_write)
         if not err and win32.GetLastError() != win32.ERROR_IO_PENDING:
             raise SerialException("WriteFile failed ({!r})".format(
                 ctypes.WinError()))
         if self._write_timeout != 0:  # if blocking (None) or w/ write timeout (>0)
             # Wait for the write to complete.
             #~ win32.WaitForSingleObject(self._overlapped_write.hEvent, win32.INFINITE)
             err = win32.GetOverlappedResult(self._port_handle,
                                             self._overlapped_write,
                                             ctypes.byref(n), True)
             if n.value != len(data):
                 raise writeTimeoutError
         return n.value
     else:
         return 0
Пример #8
0
 def write(self, data):
     '''Write data to the serial port.
     
     Parameters:
         data (bytearray): data written to the serial port.
 
     Returns:
         wrote (int): the number of data bytes written. 
     '''
     if not self.is_open:
         return None
     offset = 0
     timeout = int(
         self._write_timeout * 1000 if self._write_timeout \
             else self.USB_WRITE_TIMEOUT_MILLIS
     )
     wrote = 0
     while offset < len(data):
         data_length = min(
             len(data) - offset, self.DEFAULT_WRITE_BUFFER_SIZE)
         buf = data[offset:offset + data_length]
         i = self._connection.bulkTransfer(self._write_endpoint, buf,
                                           data_length, timeout)
         if i <= 0:
             raise SerialException("Failed to write {}: {}".format(buf, i))
         offset += data_length
         wrote += i
     return wrote
Пример #9
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()
     poll = select.poll()
     poll.register(
         self.fd,
         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(self._timeout * 1000):
                 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
             buf = os.read(self.fd, size - len(read))
             read.extend(buf)
             if ((self._timeout is not None and self._timeout >= 0) 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)
Пример #10
0
 def _connect_to_port(self):
     try:
         return serial_communication.connect(port=self._port,
                                             baudrate=TC_BAUDRATE)
     except SerialException:
         raise SerialException("Thermocycler device not found on {}".format(
             self._port))
Пример #11
0
 def _read(self):
     '''Hardware dependent read function.
     
     Returns:
         read (bytes): data bytes read from the serial port.
     '''
     if not self.is_open:
         raise portNotOpenError
     if not self._read_endpoint:
         raise SerialException("Read endpoint does not exist!")
         
     # Get raw data from hardware.
     buf = bytearray(self.DEFAULT_READ_BUFFER_SIZE)
     totalBytesRead = self._connection.bulkTransfer(
         self._read_endpoint, 
         buf, 
         self.DEFAULT_READ_BUFFER_SIZE, 
         self.USB_READ_TIMEOUT_MILLIS
     )
     if totalBytesRead < 0:
         # Read timeout. Set totalBytesRead to 0.
         totalBytesRead = 0
 
     read = buf[:totalBytesRead]
     return bytes(read)
Пример #12
0
 def ack_received(self, transaction_id, uuid):
     print("ACK received for packet!")
     if self.check_uuid(uuid) == False:
         return
     if transaction_id not in self.pending:
         raise SerialException("Invalid transaction ID received")
     del self.pending[transaction_id]
Пример #13
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
     data = bytearray()
     if self._timeout is not None:
         timeout = time.time() + self._timeout
     else:
         timeout = None
     while len(data) < size:
         try:
             # an implementation with internal buffer would be better
             # performing...
             block = self._socket.recv(size - len(data))
             if block:
                 data.extend(block)
             else:
                 # no data -> EOF (connection probably closed)
                 break
         except socket.timeout:
             # just need to get out of recv from time to time to check if
             # still alive and timeout did not expire
             pass
         except socket.error as e:
             # connection fails -> terminate loop
             raise SerialException('connection failed (%s)' % e)
         if timeout is not None and time.time() > timeout:
             break
     return bytes(data)
Пример #14
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)
Пример #15
0
    def open(self):
        """\
        Open port with current settings. This may throw a SerialException
        if the port cannot be opened."""
        if self._port is None:
            raise SerialException(
                "Port must be configured before it can be used.")
        if self.is_open:
            raise SerialException("Port is already open.")
        self.fd = None
        # open
        try:
            self.fd = os.open(self.portstr,
                              os.O_RDWR | os.O_NOCTTY | os.O_NONBLOCK)
        except OSError as msg:
            self.fd = None
            raise SerialException(
                msg.errno,
                "could not open port {}: {}".format(self._port, msg))
        #~ fcntl.fcntl(self.fd, fcntl.F_SETFL, 0)  # set blocking

        try:
            self._reconfigure_port(force_update=True)
        except:
            try:
                os.close(self.fd)
            except:
                # ignore any exception when closing the port
                # also to keep original exception that happened when setting up
                pass
            self.fd = None
            raise
        else:
            self.is_open = True
        try:
            if not self._dsrdtr:
                self._update_dtr_state()
            if not self._rtscts:
                self._update_rts_state()
        except IOError as e:
            if e.errno == 22:  # ignore Invalid argument
                pass
            else:
                raise
        self.reset_input_buffer()
        self.pipe_abort_read_r, self.pipe_abort_read_w = os.pipe()
        self.pipe_abort_write_r, self.pipe_abort_write_w = os.pipe()
Пример #16
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._port_handle:
         raise portNotOpenError
     if size > 0:
         win32.ResetEvent(self._overlapped_read.hEvent)
         flags = win32.DWORD()
         comstat = win32.COMSTAT()
         if not win32.ClearCommError(self._port_handle, ctypes.byref(flags),
                                     ctypes.byref(comstat)):
             raise SerialException('call to ClearCommError failed')
         if self.timeout == 0:
             n = min(comstat.cbInQue, size)
             if n > 0:
                 buf = ctypes.create_string_buffer(n)
                 rc = win32.DWORD()
                 err = win32.ReadFile(self._port_handle, buf, n,
                                      ctypes.byref(rc),
                                      ctypes.byref(self._overlapped_read))
                 if not err and win32.GetLastError(
                 ) != win32.ERROR_IO_PENDING:
                     raise SerialException("ReadFile failed (%r)" %
                                           ctypes.WinError())
                 err = win32.WaitForSingleObject(
                     self._overlapped_read.hEvent, win32.INFINITE)
                 read = buf.raw[:rc.value]
             else:
                 read = bytes()
         else:
             buf = ctypes.create_string_buffer(size)
             rc = win32.DWORD()
             err = win32.ReadFile(self._port_handle, buf, size,
                                  ctypes.byref(rc),
                                  ctypes.byref(self._overlapped_read))
             if not err and win32.GetLastError() != win32.ERROR_IO_PENDING:
                 raise SerialException("ReadFile failed (%r)" %
                                       ctypes.WinError())
             err = win32.GetOverlappedResult(
                 self._port_handle, ctypes.byref(self._overlapped_read),
                 ctypes.byref(rc), True)
             read = buf.raw[:rc.value]
     else:
         read = bytes()
     return bytes(read)
Пример #17
0
    def open(self):
        self.close()

        activity = cast('android.content.Context', Context.mActivity)
        manager = activity.getSystemService("usb")
        device = None
        log.info("UsbDevices: {}".format(
            manager.getDeviceList().values().toArray()))
        for device in manager.getDeviceList().values().toArray():
            if device:  # and device.getDeviceName()==self.portstr:
                log.info("Found device {}".format(device.getDeviceName()))
                break
        if not device:
            raise SerialException("Device not present {}".format(self.portstr))

        connection = manager.openDevice(device)
        if not connection:
            #if not CdcAcmSerialPort._requested_permission:
            #    intent = PendingIntent()
            #    manager.requestPermission(device,intent)
            raise SerialException("Failed to open device!")

        log.info("UsbDevice connection made {}!".format(connection))

        self._device = device
        self._connection = connection

        if device.getInterfaceCount() == 1:
            log.debug(
                "device might be castrated ACM device, trying single interface logic"
            )
            self._open_single_interface()
        else:
            log.debug("trying default interface logic")
            self._open_interface()

        #: Check that all endpoints are good
        if None in [
                self._control_endpoint, self._write_endpoint,
                self._read_endpoint
        ]:
            msg = "Could not establish all endpoints"
            log.debug(msg)
            raise SerialException(msg)

        return self.fd
Пример #18
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)
Пример #19
0
    def write(self, data):
        """Output the given byte string over the serial port."""
        if not self.is_open:
            raise PortNotOpenError()
        #~ if not isinstance(data, (bytes, bytearray)):
        #~ raise TypeError('expected %s or bytearray, got %s' % (bytes, type(data)))
        # convert data (needed in case of memoryview instance: Py 3.1 io lib), ctypes doesn't like memoryview
        data = to_bytes(data)
        if data:
            #~ win32event.ResetEvent(self._overlapped_write.hEvent)
            n = win32.DWORD()
            success = win32.WriteFile(self._port_handle, data, len(data),
                                      ctypes.byref(n), self._overlapped_write)
            if self._write_timeout != 0:  # if blocking (None) or w/ write timeout (>0)
                if not success and win32.GetLastError() not in (
                        win32.ERROR_SUCCESS, win32.ERROR_IO_PENDING):
                    raise SerialException("WriteFile failed ({!r})".format(
                        ctypes.WinError()))

                # Wait for the write to complete.
                #~ win32.WaitForSingleObject(self._overlapped_write.hEvent, win32.INFINITE)
                win32.GetOverlappedResult(self._port_handle,
                                          self._overlapped_write,
                                          ctypes.byref(n), True)
                if win32.GetLastError() == win32.ERROR_OPERATION_ABORTED:
                    return n.value  # canceled IO is no error
                if n.value != len(data):
                    raise SerialTimeoutException('Write timeout')
                return n.value
            else:
                errorcode = win32.ERROR_SUCCESS if success else win32.GetLastError(
                )
                if errorcode in (win32.ERROR_INVALID_USER_BUFFER,
                                 win32.ERROR_NOT_ENOUGH_MEMORY,
                                 win32.ERROR_OPERATION_ABORTED):
                    return 0
                elif errorcode in (win32.ERROR_SUCCESS,
                                   win32.ERROR_IO_PENDING):
                    # no info on true length provided by OS function in async mode
                    return len(data)
                else:
                    raise SerialException("WriteFile failed ({!r})".format(
                        ctypes.WinError()))
        else:
            return 0
Пример #20
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._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)
Пример #21
0
    def _open_interface(self):
        '''Open default interface device.'''
        device = self._device

        # Claiming control interface.
        self._control_interface = device.getInterface(0)
        if not self._connection.claimInterface(self._control_interface, True):
            raise SerialException("Could not claim control interface.")

        self._control_endpoint = self._control_interface.getEndpoint(0)

        # Claiming data interface.
        self._data_interface = device.getInterface(1)
        if not self._connection.claimInterface(self._data_interface, True):
            raise SerialException("Could not claim data interface.")

        self._read_endpoint = self._data_interface.getEndpoint(1)
        self._write_endpoint = self._data_interface.getEndpoint(0)
Пример #22
0
 def open(self):
     """Open the initialized serial port"""
     from serial.serialutil import SerialException
     try:
         UsbSerial.open(self, Ftdi, FtdiSerial.SCHEME,
                        FtdiSerial.VENDOR_IDS, FtdiSerial.PRODUCT_IDS,
                        FtdiSerial.DEFAULT_VENDOR)
     except FtdiError, e:
         raise SerialException(str(e))
Пример #23
0
    def open(self):
        """Open a (previously initialized) port."""
        self._logger.debug('Opening port')

        if self._isOpen:
            raise SerialException('Port is already open.')

        self._isOpen = True
        self.port = self.initial_port_name
Пример #24
0
 def _reconfigure_port(self):
     """\
     Set communication parameters on opened port. For the socket://
     protocol all settings are ignored!
     """
     if self._socket is None:
         raise SerialException("Can only operate on open ports")
     if self.logger:
         self.logger.info('ignored port configuration change')
Пример #25
0
 def _set_rts(self, state):
     '''Set rts line.
     
     Parameters:
         state (bool): new RTS logical level.
     '''
     value = state and self.SIO_SET_RTS_HIGH or self.SIO_SET_RTS_LOW
     if self._ctrl_transfer_out(self.SIO_SET_MODEM_CTRL, value,
                                self._index):
         raise SerialException('Unable to set RTS line')
Пример #26
0
 def open(self):
     """Open port with current settings. This may throw a SerialException
        if the port cannot be opened."""
     if self._port is None:
         raise SerialException(
             "Port must be configured before it can be used.")
     # not that there anything to configure...
     self._reconfigurePort()
     # all things set up get, now a clean start
     self.is_open = True
Пример #27
0
 def from_url(self, url):
     parts = urlparse.urlsplit(url)
     if parts.scheme != "cp2110":
         raise SerialException(
             'expected a string in the forms '
             '"cp2110:///dev/hidraw9" or "cp2110://0001:0023:00": '
             'not starting with cp2110:// {{!r}}'.format(parts.scheme))
     if parts.netloc:  # cp2100://BUS:DEVICE:ENDPOINT, for libusb
         return parts.netloc.encode('utf-8')
     return parts.path.encode('utf-8')
Пример #28
0
 def _set_break(self, break_):
     '''Start or stop a break exception event on the serial line.
     
     Parameters:
         break_ (bool): either start or stop break event.
     '''
     result = self._ctrl_out(self.BREAK_REQUEST,
                             self.BREAK_ON if break_ else self.BREAK_OFF, 0)
     if result != 0:
         raise SerialException('Unable to set break state!')
Пример #29
0
 def read(self, data_length):
     if not self.is_open:
         return None
     if not self._read_endpoint:
         raise SerialException("Read endpoint does not exist!")
     
     if self.ENABLE_ASYNC_READS:
         # Not implemented yet.
         return None
     else:
         buf = bytearray(data_length)
         timeout = int(self._timeout * 1000 if self._timeout else self.USB_READ_TIMEOUT_MILLIS)
         totalBytesRead = self._connection.bulkTransfer(self._read_endpoint, buf, data_length, timeout)
         if totalBytesRead < self.MODEM_STATUS_HEADER_LENGTH:
             raise SerialException("Expected at least {} bytes".format(self.MODEM_STATUS_HEADER_LENGTH))
     
         dest = bytearray()
         self.filterStatusBytes(buf, dest, totalBytesRead, self._read_endpoint.getMaxPacketSize())
         return dest
Пример #30
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 = self._write_timeout
     if timeout and timeout > 0:  # Avoid comparing None with zero
         timeout += time.time()
     while tx_len > 0:
         try:
             n = os.write(self.fd, d)
             if timeout == 0:
                 # Zero timeout indicates non-blocking - simply return the
                 # number of bytes of data actually written
                 return n
             elif timeout and timeout > 0:  # Avoid comparing None with zero
                 # when timeout is set, use select to wait for being ready
                 # with the time left as timeout
                 timeleft = timeout - time.time()
                 if timeleft < 0:
                     raise writeTimeoutError
                 _, ready, _ = select.select([], [self.fd], [], timeleft)
                 if not ready:
                     raise writeTimeoutError
             else:
                 assert timeout is None
                 # wait for write operation
                 _, ready, _ = select.select([], [self.fd], [], None)
                 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 and timeout - time.time() < 0:
                 raise writeTimeoutError
     return len(data)