Python usb.USBError() Examples

The following are 18 code examples of usb.USBError(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module usb , or try the search function .
Example #1
Source File: cfusb.py    From crazyflie-lib-python with GNU General Public License v2.0 7 votes vote down vote up
def receive_packet(self):
        dataIn = ()
        try:
            if (pyusb1 is False):
                dataIn = self.handle.bulkRead(0x81, 64, 20)
            else:
                dataIn = self.handle.read(0x81, 64, timeout=20)
        except usb.USBError as e:
            try:
                if e.backend_error_code == -7 or e.backend_error_code == -116:
                    # Normal, the read was empty
                    pass
                else:
                    raise IOError('Crazyflie disconnected')
            except AttributeError:
                # pyusb < 1.0 doesn't implement getting the underlying error
                # number and it seems as if it's not possible to detect
                # if the cable is disconnected. So this detection is not
                # supported, but the "normal" case will work.
                pass

        return dataIn


# Private utility functions 
Example #2
Source File: usbdriver.py    From alienfx with GNU General Public License v3.0 6 votes vote down vote up
def release(self):
        """ Release control to libusb of the AlienFX controller."""
        if not self._control_taken:
            return
        try:
            usb.util.release_interface(self._dev, 0)
        except USBError as exc: 
            logging.error(
                "Cant release interface. Error : {}".format(exc.strerror))
        try:
            self._dev.attach_kernel_driver(0)
        except USBError as exc: 
            logging.error("Cant re-attach. Error : {}".format(exc.strerror))
        self._control_taken = False
        logging.debug("USB device released, VID={}, PID={}".format(
            hex(self._controller.vendor_id), hex(self._controller.product_id))) 
Example #3
Source File: wmr200.py    From wfrog with GNU General Public License v3.0 6 votes vote down vote up
def disconnectDevice(self):
      import usb

      if self.devh == None:
        return

      try:
        # Tell console the session is finished.
        self.sendCommand(0xDF)
        try:
          self.devh.releaseInterface()
        except ValueError:
          None
        self.logger.info("USB connection closed")
        time.sleep(usbTimeout)
      except usb.USBError, e:
        self.logger.exception("WMR200 disconnect failed: %s" % str(e)) 
Example #4
Source File: cfusb.py    From crazyflie-lib-python with GNU General Public License v2.0 5 votes vote down vote up
def send_packet(self, dataOut):
        """ Send a packet and receive the ack from the radio dongle
            The ack contains information about the packet transmition
            and a data payload if the ack packet contained any """
        try:
            if (pyusb1 is False):
                self.handle.bulkWrite(1, dataOut, 20)
            else:
                self.handle.write(endpoint=1, data=dataOut, timeout=20)
        except usb.USBError:
            pass 
Example #5
Source File: usb.py    From pyswd with MIT License 5 votes vote down vote up
def read(self, size, timeout=200):
        """Read data from USB pipe"""
        try:
            data = self._dev.read(self.PIPE_IN, size, timeout).tobytes()
        except _usb.USBError as err:
            self._dev = None
            raise StlinkUsbException("USB Error: %s" % err)
        return data 
Example #6
Source File: usb.py    From pyswd with MIT License 5 votes vote down vote up
def write(self, data, timeout=200):
        """Write data to USB pipe"""
        try:
            count = self._dev.write(self.PIPE_OUT, data, timeout)
        except _usb.USBError as err:
            self._dev = None
            raise StlinkUsbException("USB Error: %s" % err)
        if count != len(data):
            raise StlinkUsbException("Error Sending data") 
Example #7
Source File: wmr200.py    From wfrog with GNU General Public License v3.0 5 votes vote down vote up
def sendPacket(self, packet):
      import usb
      try:
        self.devh.controlMsg(usb.TYPE_CLASS + usb.RECIP_INTERFACE,
                             0x9, packet, 0x200,
                             timeout = int(usbTimeout * 1000))
      except usb.USBError, e:
        if e.args != ('No error',):
          self.logger.exception("Can't write request record: "+ str(e))

    # The WMR200 is known to support the following commands:
    # 0xD0: Request next set of data frames.
    # 0xDA: Check if station is ready.
    # 0xDB: Clear historic data from station memory.
    # 0xDF: Not really known. Maybe to signal end of data transfer. 
Example #8
Source File: wmr200.py    From wfrog with GNU General Public License v3.0 5 votes vote down vote up
def receivePacket(self):
      import usb
      while True:
        try:
          packet = self.devh.interruptRead(usb.ENDPOINT_IN + 1, 8,
                                           int(self.pollDelay * 1000))
          self.totalPackets += 1

          # Provide some statistics on the USB connection every 1000
          # packets.
          if self.totalPackets > 0 and self.totalPackets % 1000 == 0:
            self.logStats()

          if len(packet) != 8:
            # Valid packets must always have 8 octets.
            self.badPackets += 1
            self.logger.error("Wrong packet size: %s" %
                              self._list2bytes(packet))
          elif packet[0] > 7:
            # The first octet is always the number of valid octets in the
            # packet. Since a packet can only have 8 bytes, ignore all packets
            # with a larger size value. It must be corrupted.
            self.badPackets += 1
            self.logger.error("Bad packet: %s" % self._list2bytes(packet))
          else:
            # We've received a new packet.
            self.packets += 1
            self.logger.debug("Packet: %s" % self._list2bytes(packet))
            return packet

        except usb.USBError, e:
          self.logger.debug("Exception reading interrupt: "+ str(e))
          return None 
Example #9
Source File: pyrow.py    From PyRow with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def __init__(self, erg):
        """
        Configures usb connection and sets erg value
        """

        if sys.platform != 'win32':
            try:
                #Check to see if driver is attached to kernel (linux)
                if erg.is_kernel_driver_active(INTERFACE):
                    erg.detach_kernel_driver(INTERFACE)
                else:
                    print "DEBUG: usb kernel driver not on " + sys.platform
            except:
                print "EXCEPTION"

        #Claim interface (Needs Testing To See If Necessary)
        usb.util.claim_interface(erg, INTERFACE)

        #Linux throws error, reason unknown
        try:
            erg.set_configuration() #required to configure USB connection
            #Ubuntu Linux returns 'usb.core.USBError: Resource busy' but rest of code still works
        except Exception as e:
            if not isinstance(e, USBError):
                raise e
        self.erg = erg

        configuration = erg[0]
        iface = configuration[(0, 0)]
        self.inEndpoint = iface[0].bEndpointAddress
        self.outEndpoint = iface[1].bEndpointAddress

        self.__lastsend = datetime.datetime.now() 
Example #10
Source File: usbdriver.py    From alienfx with GNU General Public License v3.0 5 votes vote down vote up
def write_packet(self, pkt):
        """ Write the given packet over USB to the AlienFX controller."""
        if not self._control_taken:
            return
        try:
            self._dev.ctrl_transfer(
                self.OUT_BM_REQUEST_TYPE, 
                self.OUT_B_REQUEST, self.OUT_W_VALUE, 
                self.OUT_W_INDEX, pkt, 0)
        except USBError as exc:
            logging.error("write_packet: {}".format(exc)) 
Example #11
Source File: crazyradio.py    From crazyflie-lib-python with GNU General Public License v2.0 5 votes vote down vote up
def send_packet(self, dataOut):
        """ Send a packet and receive the ack from the radio dongle
            The ack contains information about the packet transmition
            and a data payload if the ack packet contained any """
        ackIn = None
        data = None
        try:
            if (pyusb1 is False):
                self.handle.bulkWrite(1, dataOut, 1000)
                data = self.handle.bulkRead(0x81, 64, 1000)
            else:
                self.handle.write(endpoint=1, data=dataOut, timeout=1000)
                data = self.handle.read(0x81, 64, timeout=1000)
        except usb.USBError:
            pass

        if data is not None:
            ackIn = _radio_ack()
            if data[0] != 0:
                ackIn.ack = (data[0] & 0x01) != 0
                ackIn.powerDet = (data[0] & 0x02) != 0
                ackIn.retry = data[0] >> 4
                ackIn.data = data[1:]
            else:
                ackIn.retry = self.arc

        return ackIn


# Private utility functions 
Example #12
Source File: radiodriver.py    From crazyflieROS with GNU General Public License v2.0 5 votes vote down vote up
def get_status(self):
        if self.cradio is None:
            try:
                self.cradio = Crazyradio()
            except USBError as e:
                return "Cannot open Crazyradio. Permission problem?"\
                       " ({})".format(str(e))
            except Exception as e:
                return str(e)

        return "Crazyradio version {}".format(self.cradio.version) 
Example #13
Source File: crazyradio.py    From crazyflieROS with GNU General Public License v2.0 5 votes vote down vote up
def send_packet(self, dataOut):
        """ Send a packet and receive the ack from the radio dongle
            The ack contains information about the packet transmition
            and a data payload if the ack packet contained any """
        ackIn = None
        data = None
        try:
            if (pyusb1 is False):
                self.handle.bulkWrite(1, dataOut, 1000)
                data = self.handle.bulkRead(0x81, 64, 1000)
            else:
                self.handle.write(1, dataOut, 0, 1000)
                data = self.handle.read(0x81, 64, 0, 1000)
        except usb.USBError:
            pass

        if data is not None:
            ackIn = _radio_ack()
            if data[0] != 0:
                ackIn.ack = (data[0] & 0x01) != 0
                ackIn.powerDet = (data[0] & 0x02) != 0
                ackIn.retry = data[0] >> 4
                ackIn.data = data[1:]
            else:
                ackIn.retry = self.arc

        return ackIn


#Private utility functions 
Example #14
Source File: usb.py    From pyvisa-py with MIT License 5 votes vote down vote up
def read(self, count):
        """Reads data from device or interface synchronously.

        Corresponds to viRead function of the VISA library.

        :param count: Number of bytes to be read.
        :return: data read, return value of the library call.
        :rtype: (bytes, VISAStatus)
        """

        def _usb_reader():
            """Data reader identifying usb timeout exception."""
            try:
                return self.interface.read(count)
            except usb.USBError as exc:
                if exc.errno in (errno.ETIMEDOUT, -errno.ETIMEDOUT):
                    raise USBTimeoutException()
                raise

        supress_end_en, _ = self.get_attribute(constants.VI_ATTR_SUPPRESS_END_EN)

        if supress_end_en:
            raise ValueError(
                "VI_ATTR_SUPPRESS_END_EN == True is currently unsupported by pyvisa-py"
            )

        term_char, _ = self.get_attribute(constants.VI_ATTR_TERMCHAR)
        term_char_en, _ = self.get_attribute(constants.VI_ATTR_TERMCHAR_EN)

        return self._read(
            _usb_reader,
            count,
            lambda current: True,  # USB always returns a complete message
            supress_end_en,
            term_char,
            term_char_en,
            USBTimeoutException,
        ) 
Example #15
Source File: usbdriver.py    From alienfx with GNU General Public License v3.0 5 votes vote down vote up
def acquire(self):
        """ Acquire control from libusb of the AlienFX controller."""
        if self._control_taken:
            return
        self._dev = usb.core.find(
            idVendor=self._controller.vendor_id, 
            idProduct=self._controller.product_id)
        if (self._dev is None):
            msg = "ERROR: No AlienFX USB controller found; tried "
            msg += "VID {}".format(self._controller.vendor_id)
            msg += ", PID {}".format(self._controller.product_id)
            logging.error(msg)
        try:
            self._dev.detach_kernel_driver(0)
        except USBError as exc: 
            logging.error(
                "Cant detach kernel driver. Error : {}".format(exc.strerror))
        try:
            self._dev.set_configuration()
        except USBError as exc: 
            logging.error(
                "Cant set configuration. Error : {}".format(exc.strerror))
        try:
            usb.util.claim_interface(self._dev, 0)
        except USBError as exc: 
            logging.error(
                "Cant claim interface. Error : {}".format(exc.strerror))
        self._control_taken = True
        logging.debug("USB device acquired, VID={}, PID={}".format(
            hex(self._controller.vendor_id), hex(self._controller.product_id))) 
Example #16
Source File: usbdriver.py    From alienfx with GNU General Public License v3.0 5 votes vote down vote up
def read_packet(self):
        """ Read a packet over USB from the AlienFX controller and return it."""
        if not self._control_taken:
            logging.error("read_packet: control not taken...")
            return
        try:
            pkt = self._dev.ctrl_transfer(
                self.IN_BM_REQUEST_TYPE, 
                self.IN_B_REQUEST, self.IN_W_VALUE, 
                self.IN_W_INDEX, self._controller.cmd_packet.PACKET_LENGTH, 0)
            return pkt
        except USBError as exc:
            logging.error("read_packet: {}".format(exc)) 
Example #17
Source File: cfusb.py    From crazyflie-lib-python with GNU General Public License v2.0 4 votes vote down vote up
def get_serial(self):
        # The signature for get_string has changed between versions to 1.0.0b1,
        # 1.0.0b2 and 1.0.0. Try the old signature first, if that fails try
        # the newer one.
        try:
            return usb.util.get_string(self.dev, 255, self.dev.iSerialNumber)
        except (usb.core.USBError, ValueError):
            return usb.util.get_string(self.dev, self.dev.iSerialNumber) 
Example #18
Source File: wmrs200.py    From wfrog with GNU General Public License v3.0 4 votes vote down vote up
def run(self, generate_event, send_event):
        import usb

        # Initialize injected functions used by BaseStation
        self.generate_event = generate_event
        self.send_event = send_event
        self.logger.info("Thread started")
        while True:
            try:
                self.logger.info("USB initialization")
                dev = self._search_device(vendor_id, product_id)
                if dev == None:
                    raise Exception("USB WMRS200 not found (%04X %04X)" % (vendor_id, product_id))

                self.logger.info("USB WMRS200 found")
                devh = dev.open()
                self.logger.info("USB WMRS200 open")

                if platform.system() is 'Windows':
                    devh.setConfiguration(1)

                try:
                    devh.claimInterface(0)
                except usb.USBError:
                    devh.detachKernelDriver(0)
                    devh.claimInterface(0)

                # WMRS200 Init sequence
                devh.controlMsg(usb.TYPE_CLASS + usb.RECIP_INTERFACE,       # requestType
                                0x0000009,                                  # request
                                [0x20,0x00,0x08,0x01,0x00,0x00,0x00,0x00],  # buffer
                                0x0000200,                                  # value
                                0x0000000,                                  # index
                                1000)                                       # timeout

                ## Do the actual work
                self.logger.info("USB WMRS200 initialized")
                self._run(devh)

            except Exception, e:
                self.logger.exception("WMRS200 exception: %s" % str(e))

            self.logger.critical("USB WMRS200 connection failure")

            ## Wait 10 seconds
            time.sleep(10)